MongoDB Delete Document (CRUD) Tutorial

In this MongoDB tutorial we learn the fourth and final CRUD operation, deleting documents.

We cover how to delete single documents, ones that match a condition or all documents in a collection.

How to delete a document from a collection

To delete a document from a collection we use the db.collection.remove() method.

This method takes two arguments.

  • Query Document specifies the deletion criteria
  • justOne to limit the deletion operation to just one document (default is false)
Syntax:
db.collection.remove(query, justOne)

As an example, consider that we have two people in a ‘users’ collection.

Example:
db.users.insert([
    { "name" : "John", "age" : 33 },
    { "name" : "Jane", "age" : 28 },
    { "name" : "Jack", "age" : 30 },
    { "name" : "Jill", "age" : 27 }
])

Now let’s say one of the users deleted their account and we want to delete them from the database.

We can query the collection for a document that matches their name and then limit the deletion to the first document found.

Example:
db.users.remove({ "name" : "John" }, true)

If the operation is successful, it will return the number of documents removed.

Output:
WriteResult({ "nRemoved" : 1 })

In this case we limited it to only remove the first one it found.

If there were multiple users with the name “John” and we didn’t specify the limit, it would delete all of them.

How to delete documents that match a condition

MongoDB allows us to specify conditional queries to find and remove documents. To do this we simple add our conditional query, wrapped in curly braces, as the first argument.

For example, if we want to remove all the users under the age of 30, we could use the $lt meta operator on the “age” key.

Example:
db.users.remove({
    "age" : {$lt : 30}
})
Output:
WriteResult({ "nRemoved" : 2 })

How to delete all documents from a collection

To delete all the documents in a collection, all we need to do is specify an empty pair of curly braces for the first argument of the remove() method.

Example:
db.collection.remove( {} )

If the deletion was successful it will return the number of documents deleted.

Output:
WriteResult({ "nRemoved" : 1 })

In our case we only had a single entry left so it only removed 1.