Easy Tutorial
❮ Mongodb Aggregate Mongodb Dropdatabase ❯

MongoDB Deleting Documents

In the previous chapters, we have learned how to add and update data in MongoDB collections. In this chapter, we will continue to learn about deleting documents from MongoDB collections.

The remove() function in MongoDB is used to remove data from a collection.

Data updates in MongoDB can be performed using the update() function. It is a good practice to execute the find() command before the remove() function to ensure the conditions are correct.

Syntax

The basic syntax format for the remove() method is as follows:

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

For MongoDB versions 2.6 and later, the syntax format is:

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

Parameter Description:

Example

We will perform two insert operations with the following documents:

>db.col.insert({title: 'MongoDB Tutorial', 
    description: 'MongoDB is a NoSQL database',
    by: 'tutorialpro.org',
    url: 'http://www.tutorialpro.org',
    tags: ['mongodb', 'database', 'NoSQL'],
    likes: 100
})

Use the find() function to query the data:

> db.col.find()
{ "_id" : ObjectId("56066169ade2f21f36b03137"), "title" : "MongoDB Tutorial", "description" : "MongoDB is a NoSQL database", "by" : "tutorialpro.org", "url" : "http://www.tutorialpro.org", "tags" : [ "mongodb", "database", "NoSQL" ], "likes" : 100 }
{ "_id" : ObjectId("5606616dade2f21f36b03138"), "title" : "MongoDB Tutorial", "description" : "MongoDB is a NoSQL database", "by" : "tutorialpro.org", "url" : "http://www.tutorialpro.org", "tags" : [ "mongodb", "database", "NoSQL" ], "likes" : 100 }

Next, we will remove the documents with the title 'MongoDB Tutorial':

>db.col.remove({'title':'MongoDB Tutorial'})
WriteResult({ "nRemoved" : 2 })           # Two documents were deleted
>db.col.find()
……                                        # No data

If you want to delete only 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 in regular SQL):

>db.col.remove({})
>db.col.find()
>
❮ Mongodb Aggregate Mongodb Dropdatabase ❯