如何从集合中删除除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"
}以下是从集合中删除所有文档的查询,除了单个文档,即使用StudentAge24
> db.removeAllDocumentsExceptOneDemo.remove({ StudentAge: { $ne: 24 } } );
WriteResult({ "nRemoved" : 2 })现在让我们检查所有文件。以下是查询
> db.removeAllDocumentsExceptOneDemo.find().pretty();
以下是仅显示单个文档的输出
{
"_id" : ObjectId("5c9c9def2d6669774125247a"),
"StudentName" : "Chris",
"StudentAge" : 24,
"StudentCountryName" : "AUS"
}热门推荐
10 财运虎年祝福语简短语
11 单亲爸爸春节祝福语简短
12 狗狗上厕所训练
13 植物种植祝福语简短
14 翻译考试祝福语朋友简短
15 个人周年庆简短祝福语
16 狗狗怎么训练
17 分别祝福语简短搞笑英文
18 生日广州男生祝福语简短