Latest web development tutorials

MongoDB delete documents

In the previous sections, we have learned how to MongoDB data collection to add and update data. In this section we will continue to learn deleted MongoDB collection.

MongoDB remove () function is used to remove the data collection.

MongoDB data updates can use update () function. Performing remove () function first before execution find () command to determine whether the conditions to perform correctly, this is a good habit.

grammar

The basic syntax remove () method is as follows:

db.collection.remove(
   <query>,
   <justOne>
)

If your MongoDB version 2.6 later, syntax is as follows:

db.collection.remove(
   <query>,
   {
     justOne: <boolean>,
     writeConcern: <document>
   }
)

Parameter Description:

  • query :( optional) condition of the document deleted.
  • justOne: (Optional) If set to true or 1, only to delete a document.
  • writeConcern :( optional) level exception is thrown.

Examples

The following document we perform two insertions:

>db.col.insert({title: 'MongoDB 教程', 
    description: 'MongoDB 是一个 Nosql 数据库',
    by: '本教程',
    url: 'http://www.w3big.com',
    tags: ['mongodb', 'database', 'NoSQL'],
    likes: 100
})

Using the find () function to query the data:

> db.col.find()
{ "_id" : ObjectId("56066169ade2f21f36b03137"), "title" : "MongoDB 教程", "description" : "MongoDB 是一个 Nosql 数据库", "by" : "本教程", "url" : "http://www.w3big.com", "tags" : [ "mongodb", "database", "NoSQL" ], "likes" : 100 }
{ "_id" : ObjectId("5606616dade2f21f36b03138"), "title" : "MongoDB 教程", "description" : "MongoDB 是一个 Nosql 数据库", "by" : "本教程", "url" : "http://www.w3big.com", "tags" : [ "mongodb", "database", "NoSQL" ], "likes" : 100 }

Next, we remove the title of 'MongoDB tutorial' documents:

>db.col.remove({'title':'MongoDB 教程'})
WriteResult({ "nRemoved" : 2 })           # 删除了两条数据
>db.col.find()
……                                        # 没有数据

If you want to delete the first record found can be set justOne 1, as follows:

>db.COLLECTION_NAME.remove(DELETION_CRITERIA,1)

If you want to delete all data, you can use the following methods (similar to the conventional SQL truncate the command):

>db.col.remove({})
>db.col.find()
>