如何使用 deleteOne() 方法从 MongoDB 集合中删除文档?

mongodbbig data analyticsdatabase

要从 MongoDB 集合中删除文档,可以使用 deleteOne() 方法。首先,创建一个集合并向其中插入一些文档:

> db.deleteDocumentsDemo.insert({"Name":"Larry","Age":23});
WriteResult({ "nInserted" : 1 })
> db.deleteDocumentsDemo.insert({"Name":"Mike","Age":21});
WriteResult({ "nInserted" : 1 })
> db.deleteDocumentsDemo.insert({"Name":"Sam","Age":24});
WriteResult({ "nInserted" : 1 })

现在显示集合中的所有文档。查询如下:

> db.deleteDocumentsDemo.find().pretty();

输出结果如下:

{
   "_id" : ObjectId("5c6ab0e064f3d70fcc914805"),
   "Name" : "Larry",
   "Age" : 23
}
{
   "_id" : ObjectId("5c6ab0ef64f3d70fcc914806"),
   "Name" : "Mike",
   "Age" : 21
}
{ "_id" : ObjectId("5c6ab0f864f3d70fcc914807"), "Name" : "Sam", "Age" : 24 }

现在使用 deleteOne() 命令。顾名思义,该命令只会从集合中删除一个文档。查询语句如下:

> db.deleteDocumentsDemo.deleteOne({"Name":"Larry"});

输出结果如下:

{ "acknowledged" : true, "deletedCount" : 1 }

现在使用 find() 命令显示集合中的文档。查询语句如下:

> db.deleteDocumentsDemo.find().pretty();

输出结果如下:

{
   "_id" : ObjectId("5c6ab0ef64f3d70fcc914806"),
   "Name" : "Mike",
   "Age" : 21
}
{ "_id" : ObjectId("5c6ab0f864f3d70fcc914807"), "Name" : "Sam", "Age" : 24 }

查看上面的示例输出,没有包含字段 Name: “Larry” 的文档。


相关文章