如何从集合中删除除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 红包祝福语简短10字
18 周六早晨祝福语简短