Sling Academy
Home/MongoDB/MongoDB remove() method – Explained with examples

MongoDB remove() method – Explained with examples

Last updated: February 03, 2024

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.

Next Article: MongoDB: How to retry on read/write failure (with examples)

Previous Article: MongoDB deleteMany() method: A developer’s guide (with examples)

Series: MongoDB Tutorials

MongoDB

You May Also Like

  • MongoDB: How to combine data from 2 collections into one
  • Hashed Indexes in MongoDB: A Practical Guide
  • Partitioning and Sharding in MongoDB: A Practical Guide (with Examples)
  • Geospatial Indexes in MongoDB: How to Speed Up Geospatial Queries
  • Understanding Partial Indexes in MongoDB
  • Exploring Sparse Indexes in MongoDB (with Examples)
  • Using Wildcard Indexes in MongoDB: An In-Depth Guide
  • Matching binary values in MongoDB: A practical guide (with examples)
  • Understanding $slice operator in MongoDB (with examples)
  • Caching in MongoDB: A practical guide (with examples)
  • CannotReuseObject Error: Attempted illegal reuse of a Mongo object in the same process space
  • How to perform cascade deletion in MongoDB (with examples)
  • MongoDB: Using $not and $nor operators to negate a query
  • MongoDB: Find SUM/MIN/MAX/AVG of each group in a collection
  • References (Manual Linking) in MongoDB: A Developer’s Guide (with Examples)
  • MongoDB: How to see all fields in a collection (with examples)
  • Type checking in MongoDB: A practical guide (with examples)
  • How to query an array of subdocuments in MongoDB (with examples)
  • MongoDB: How to compare 2 documents (with examples)