MongoDB remove() method – Explained with examples

Updated: February 3, 2024 By: Guest Contributor Post a comment

Overview

When working with MongoDB, one of the fundamental operations you’ll need to perform is deleting documents from your collections. The remove() method in MongoDB is one of the primary tools used to achieve this. In this tutorial, we’ll explore how to use the remove() method, including its syntax and various examples.

Getting Started with remove()

MongoDB is a NoSQL, document-oriented database that stores data in flexible, JSON-like documents. The remove() method is a part of MongoDB’s native CRUD (Create, Read, Update, Delete) operations. Using this method, you can delete single or multiple documents from a collection that match a given query criteria.

// Basic syntax
 db.collection.remove(query, justOne)

The query parameter specifies the selection criteria for the deletion. If you omit the query object, all documents within the collection will be removed. The justOne is an optional boolean parameter that, when set to true, causes the method to remove only a single document matching the query criteria.

Basic Example

Let’s start with a straightforward example where we remove a single document from the ‘users’ collection that matches a specific criterion.

db.users.remove({ 'name': 'John' })

This command will remove all documents from the ‘users’ collection where the ‘name’ field is equal to ‘John’. If there are multiple documents that match, they will all be deleted.

Removing Just One Document

If you want to remove only the first document that matches the criterion, you can use the justOne parameter like so:

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

This command will remove only the first document found with ‘name’ equal to ‘John’.

Conditional Removal

You can also perform removals that meet certain conditions. For example, if you want to delete users who are older than 30:

db.users.remove({ 'age': { '$gt': 30 } })

In this case, all users in the ‘users’ collection with an ‘age’ greater than 30 will be removed.

Removing Without a Condition

To remove all documents from a collection, simply use an empty query object:

db.users.remove({})

Be cautious with this operation, as it will wipe all data from the ‘users’ collection.

Advanced Removal Examples

Beyond single attribute matches, MongoDB allows for much more complex queries.

If we wanted to remove all users that either have an ‘age’ less than 20 or a ‘name’ that starts with ‘S’, we would use the $or operator:

db.users.remove({
  '$or': [
    { 'age': { '$lt': 20 } },
    { 'name': /^S/ }
  ]
})

This query matches any user who is either under 20 years old or has a name beginning with ‘S’, and then removes those documents from the collection.

Another advanced example is using the $in operator to remove users with specific names:

db.users.remove({
  'name': {
    '$in': ['Alice', 'Bob', 'Charlie']
  }
})

Here, any user named ‘Alice’, ‘Bob’, or ‘Charlie’ would be deleted from the ‘users’ collection.

Handling Output

When you issue a remove command in MongoDB, it returns a document containing the field nRemoved, which indicates how many documents were deleted.

var result = db.users.remove({ 'name': 'John' });
print('Documents deleted: ' + result.nRemoved);

This snippet prints the number of documents that were removed by the remove operation.

Safe Deletes

To ensure the integrity of your operations, you might opt for ‘safe’ deletes, where you first check if the document exists, then remove it.

if (db.users.findOne({ 'name': 'John' })) {
    db.users.remove({ 'name': 'John' });
}

This code safely removes ‘John’ only if the document exists, preventing unnecessary database operations.

Conclusion

In this tutorial, we’ve covered the MongoDB remove() method comprehensively. We walked through basic usage scenarios as well as more complex examples involving conditional removals. Remember, while the remove() method is potent, it should be used with caution to avoid accidental data loss.