如何从 MongoDB 的集合中删除文档?
要从MongoDB的集合中删除文档,您需要使用remove()方法。语法如下:
db.yourCollectionName.remove(yourDeleteValue);
在这里,让我们创建一个包含一些文档的集合。查询如下:
>db.deleteDocuments.insert({"UserId":1,"UserName":"Bob","UserTechnicalSubject":"Introducti on to PL/SQL"}); WriteResult({ "nInserted" : 1 }) >db.deleteDocuments.insert({"UserId":2,"UserName":"Carol","UserTechnicalSubject":"Introduction to MongoDB"}); WriteResult({ "nInserted" : 1 }) >db.deleteDocuments.insert({"UserId":3,"UserName":"John","UserTechnicalSubject":"Introduction to MySQL"}); WriteResult({ "nInserted" : 1 }) >db.deleteDocuments.insert({"UserId":4,"UserName":"Maxwell","UserTechnicalSubject":"Introduction to SQL Server"}); WriteResult({ "nInserted" : 1 })
您可以在find()命令的帮助下显示我们上面创建的集合中的所有文档。查询如下:
> db.deleteDocuments.find().pretty();
以下是输出:
{ "_id" : ObjectId("5c6aaa9e64f3d70fcc9147ff"), "UserId" : 1, "UserName" : "Bob", "UserTechnicalSubject" : "Introduction to PL/SQL" } { "_id" : ObjectId("5c6aaab464f3d70fcc914800"), "UserId" : 2, "UserName" : "Carol", "UserTechnicalSubject" : "Introduction to MongoDB" } { "_id" : ObjectId("5c6aaac764f3d70fcc914801"), "UserId" : 3, "UserName" : "John", "UserTechnicalSubject" : "Introduction to MySQL" } { "_id" : ObjectId("5c6aaadc64f3d70fcc914802"), "UserId" : 4, "UserName" : "Maxwell", "UserTechnicalSubject" : "Introduction to SQL Server" }
删除单个文档
要从集合中删除单个文档,您需要使用remove()方法。查询如下。假设我们要删除带有“UserId:4”的文档:
>db.deleteDocuments.remove({"UserId":4,"UserName":"Maxwell","UserTechnicalSubject":"Int roduction to SQL Server"}); WriteResult({ "nRemoved" : 2 })
现在您可以借助find()命令显示所有文档,以验证“UserId:4”文档是否已成功删除。查询如下:
> db.deleteDocuments.find().pretty();
以下是输出:
{ "_id" : ObjectId("5c6aaa9e64f3d70fcc9147ff"), "UserId" : 1, "UserName" : "Bob", "UserTechnicalSubject" : "Introduction to PL/SQL" } { "_id" : ObjectId("5c6aaab464f3d70fcc914800"), "UserId" : 2, "UserName" : "Carol", "UserTechnicalSubject" : "Introduction to MongoDB" } { "_id" : ObjectId("5c6aaac764f3d70fcc914801"), "UserId" : 3, "UserName" : "John", "UserTechnicalSubject" : "Introduction to MySQL" }
删除所有文件
要删除所有文档,您需要使用以下语法:
db.yourCollectionName.remove({ });
查询如下:
> db.deleteDocuments.remove({});
以下是输出:
WriteResult({ "nRemoved" : 3 })
我们已经从集合“deleteDocuments”中删除了所有文档: