Mongodb 简明教程
MongoDB - Delete Document
在本章中,我们将了解如何通过 MongoDB 删除文档。
In this chapter, we will learn how to delete a document using MongoDB.
The remove() Method
MongoDB 的 remove() 方法用于从集合中移除文档。remove() 方法接受两个参数。一个是删除条件,第二个是 justOne 标志。
MongoDB’s remove() method is used to remove a document from the collection. remove() method accepts two parameters. One is deletion criteria and second is justOne flag.
-
deletion criteria − (Optional) deletion criteria according to documents will be removed.
-
justOne − (Optional) if set to true or 1, then remove only one document.
Syntax
remove() 方法的基本语法如下 -
Basic syntax of remove() method is as follows −
>db.COLLECTION_NAME.remove(DELLETION_CRITTERIA)
Example
考虑 mycol 集合具有以下数据。
Consider the mycol collection has the following data.
{_id : ObjectId("507f191e810c19729de860e1"), title: "MongoDB Overview"},
{_id : ObjectId("507f191e810c19729de860e2"), title: "NoSQL Overview"},
{_id : ObjectId("507f191e810c19729de860e3"), title: "Tutorials Point Overview"}
以下示例将移除所有标题为“MongoDB Overview” 的文档。
Following example will remove all the documents whose title is 'MongoDB Overview'.
>db.mycol.remove({'title':'MongoDB Overview'})
WriteResult({"nRemoved" : 1})
> db.mycol.find()
{"_id" : ObjectId("507f191e810c19729de860e2"), "title" : "NoSQL Overview" }
{"_id" : ObjectId("507f191e810c19729de860e3"), "title" : "Tutorials Point Overview" }
Remove Only One
如果有多个记录并且您只想删除第一个记录,请在 remove() 方法中设置 justOne 参数。
If there are multiple records and you want to delete only the first record, then set justOne parameter in remove() method.
>db.COLLECTION_NAME.remove(DELETION_CRITERIA,1)
Remove All Documents
如果您没有指定删除条件,则 MongoDB 将从集合中删除整个文档。 This is equivalent of SQL’s truncate command.
If you don’t specify deletion criteria, then MongoDB will delete whole documents from the collection. This is equivalent of SQL’s truncate command.
> db.mycol.remove({})
WriteResult({ "nRemoved" : 2 })
> db.mycol.find()
>