如何在 MongoDB 中只保留单一文档,删除集合中的所有其他文档?
要在 MongoDB 中只保留单一文档,删除集合中的所有其他文档,请根据某些条件使用 remove()。让我们创建一个包含文档的集合。以下是要查询的内容
>db.removeAllDocumentsExceptOneDemo.insertOne({"StudentName":"Larry","StudentAge":21});
{
"acknowledged" : true,
"insertedId" : ObjectId("5c9c9de42d66697741252478")
}
>db.removeAllDocumentsExceptOneDemo.insertOne({"StudentName":"Mike","StudentAge":21,"StudentCountryName":"US"});
{
"acknowledged" : true,
"insertedId" : ObjectId("5c9c9dea2d66697741252479")
}
>db.removeAllDocumentsExceptOneDemo.insertOne({"StudentName":"Chris","StudentAge":24,"StudentCountryName":"AUS"});
{
"acknowledged" : true,
"insertedId" : ObjectId("5c9c9def2d6669774125247a")
}以下是使用 find() 方法显示集合中所有文档的查询内容
> db.removeAllDocumentsExceptOneDemo.find().pretty();
这将生成以下输出
{
"_id" : ObjectId("5c9c9de42d66697741252478"),
"StudentName" : "Larry",
"StudentAge" : 21
}
{
"_id" : ObjectId("5c9c9dea2d66697741252479"),
"StudentName" : "Mike",
"StudentAge" : 21,
"StudentCountryName" : "US"
}
{
"_id" : ObjectId("5c9c9def2d6669774125247a"),
"StudentName" : "Chris",
"StudentAge" : 24,
"StudentCountryName" : "AUS"
}以下是删除集合中除单一文档(即 StudentAge 为 24)之外的所有文档的查询内容
> db.removeAllDocumentsExceptOneDemo.remove({ StudentAge: { $ne: 24 } } );
WriteResult({ "nRemoved" : 2 })现在让我们检查所有文档。以下是查询内容
> db.removeAllDocumentsExceptOneDemo.find().pretty();
以下是仅显示单一文档的输出
{
"_id" : ObjectId("5c9c9def2d6669774125247a"),
"StudentName" : "Chris",
"StudentAge" : 24,
"StudentCountryName" : "AUS"
}
广告
数据结构
网络
RDBMS
操作系统
Java
iOS
HTML
CSS
Android
Python
C 程序设计
C++
C#
MongoDB
MySQL
JavaScript
PHP