MongoDB
Remove by _id
Database Management
MongoDB Console
Data Deletion

Remove by _id in MongoDB console

System Design practice on Codemia

Work through 120+ system design problems with detailed solutions, from rate limiters to multi-region storage.

Practice system design

Removing Documents by _id in MongoDB

MongoDB, a popular NoSQL database, is designed for flexibility and scalability, allowing the storage of data in the JSON-like BSON format. One of the core features of MongoDB is the ability to efficiently perform CRUD (Create, Read, Update, Delete) operations on collections of documents. Among these operations, deletion of documents by their unique identifier _id is a common requirement. This article will delve into the technical details of removing documents by _id in the MongoDB console.

Understanding the _id Field

In MongoDB, every document has a unique _id field, which serves as a primary key. When inserting documents, MongoDB automatically generates a unique ObjectId for this field if it is not provided by the user. The _id field guarantees uniqueness within a collection, thus making it a reliable identifier for operations such as updates or deletes.

Using the remove() Method

To remove a document by its _id, you can use the remove() method in the MongoDB shell, a part of their Console. This method provides a straightforward interface to specify criteria for document deletion. The command generally follows this syntax:

javascript
1db.collection.remove(
2  <query>,
3  <justOne>
4)

Parameters:

  • <query>: A document that specifies the criteria for deletion. To remove by _id, you provide a criterion document like &#123;"_id": ObjectId("yourObjectId")&#125;.
  • <justOne> (optional): A boolean determining whether to remove only one document (defaults to false).

Example: Removing a Document by _id

  1. Connecting to Your MongoDB Database
    Before performing any operations, ensure you have connected to your MongoDB instance. This typically involves opening the MongoDB shell and selecting the database you're working with.
javascript
   use yourDatabaseName
  1. Identifying the Document to Remove
    First, fetch the document you want to delete to verify its _id. For instance:
javascript
   db.users.findOne({ name: "John Doe" })

Let's assume the output returns:

json
1   {
2     "_id": ObjectId("60c72b2f9af1fef7a84090eb"),
3     "name": "John Doe",
4     "email": "[email protected]"
5   }
  1. Executing the remove() Method
    Use the fetched _id to remove the document:
javascript
   db.users.remove({ "_id": ObjectId("60c72b2f9af1fef7a84090eb") })

This command removes the document associated with that specific _id.

Notes on Deprecation

It's worth mentioning that starting from MongoDB 3.2, the remove() method was deprecated in favor of the deleteOne() and deleteMany() methods, which offer more clarity and options for bulk operations.

  • deleteOne(): Removes a single document based on a filter.
javascript
  db.collection.deleteOne({ "_id": ObjectId("yourObjectId") })
  • deleteMany(): Removes multiple documents matching a filter, though for an _id based query, it behaves the same as deleteOne().
javascript
  db.collection.deleteMany({ "_id": ObjectId("yourObjectId") })

Additional Considerations

  • Atomicity: Removing a document by _id is atomic, meaning that the operation will either fully succeed or fail, with no intermediate states.
  • Indexes: MongoDB automatically indexes _id, allowing for fast lookups when removing documents.

Summary Table

Key AspectDescription
_id FieldUnique identifier for each document
remove() MethodSyntax: db.collection.remove(query)
Deprecation NoticeUse deleteOne() instead from version 3.2
AtomicityOperations on _id are atomic
Automatic Index_id is automatically indexed for performance

Conclusion

Removing documents by _id in MongoDB is a critical operation, often required for maintaining data integrity and management within a collection. Understanding how to effectively use the remove() method and its modern alternatives like deleteOne() enhances both performance and clarity in database manipulation tasks. As MongoDB evolves, staying updated with its methods and best practices ensures that your database operations remain efficient and error-free.


Related reading
Course
Beginner
27 lessons
10 hours
System Design Fundamentals

Build a strong foundation in designing scalable, reliable distributed systems.

View the course
Track what you have practised

A free account saves your progress, solutions and study plan across every problem on Codemia.

System Design practice on Codemia

Work through 120+ system design problems with detailed solutions, from rate limiters to multi-region storage.

Practice system design

All Rights Reserved.