MongoDB delete document
In the previous chapters we have learned how to add and update data to collections in MongoDB. In this chapter we will continue to learn about deletion of MongoDB collections.
MongoDB remove() function is used to remove data from the collection.
MongoDB data update can use the update() function. It is a good habit to execute the find() command before executing the remove() function to determine whether the execution conditions are correct.
Syntax
The basic syntax format of the remove() method is as follows:
db.collection.remove( <query>, <justOne> )
If your MongoDB is version 2.6 or later, the syntax format is as follows:
db.collection.remove( <query>, { justOne: <boolean>, writeConcern: <document> } )
Parameter description:
query : (Optional) Conditions for deleted documents.
justOne : (Optional) If set to true or 1, only one document will be deleted.
writeConcern : (Optional) The level at which the exception is thrown.
Example
We perform two insertion operations on the following documents:
>db.col.insert({title: 'MongoDB 教程', description: 'MongoDB 是一个 Nosql 数据库', by: 'php中文网', url: 'http://www.php.cn', tags: ['mongodb', 'database', 'NoSQL'], likes: 100 })
Use the find() function to query data:
> db.col.find() { "_id" : ObjectId("56066169ade2f21f36b03137"), "title" : "MongoDB 教程", "description" : "MongoDB 是一个 Nosql 数据库", "by" : "php中文网", "url" : "http://www.php.cn", "tags" : [ "mongodb", "database", "NoSQL" ], "likes" : 100 } { "_id" : ObjectId("5606616dade2f21f36b03138"), "title" : "MongoDB 教程", "description" : "MongoDB 是一个 Nosql 数据库", "by" : "php中文网", "url" : "http://www.php.cn", "tags" : [ "mongodb", "database", "NoSQL" ], "likes" : 100 }
Next, we remove the document with the title 'MongoDB Tutorial':
>db.col.remove({'title':'MongoDB 教程'}) WriteResult({ "nRemoved" : 2 }) # 删除了两条数据 >db.col.find() …… # 没有数据
If you only want to delete the first found record, you can set justOne to 1, as shown below:
>db.COLLECTION_NAME.remove(DELETION_CRITERIA,1)
If you want to delete all data, you can use the following method (similar to the truncate command of regular SQL):
>db.col.remove({}) >db.col.find() >