Page Content

Tutorials

How do I Delete a Document in MongoDB?

Delete a Document in MongoDB

MongoDB lets you delete documents or groups of documents. In older versions, db.collection.remove() was the main approach, while current versions give specific methods like deleteOne() and deleteMany().

Documents are deleted using db.collection.remove(). To determine which documents to eliminate, it uses a query criteria document as its first parameter.

Delete a Document in MongoDB
Delete a Document in MongoDB
  • Removing Documents by Criteria: You supply a query document to eliminate all documents that meet a particular condition. Using the example of deleting all papers with the title ‘MongoDB Overview’ from the mycol collection:
    • This process will eliminate all documents that match.
  • Removing a Single Document:  remove() may by default delete more than one document if several documents meet the criteria. You can specify the justOne parameter to true or 1 as the second argument to guarantee that only one document is deleted, usually the first one discovered that satisfies the requirements.
    • Indexes, updates, and insertion order all affect which document gets deleted.
  • Removing All Documents in a Collection: You can use the remove() function with an empty query document {} to delete every document from a collection.
    • The indices are not eliminated by this way.
  • Warning about References: Any references to a deleted document that may still be found in other papers will be kept in the database. Those references will return null when evaluated until you actively remove or update them.

Newer Document Deletion Methods (MongoDB 3.2+)

To make document deletion more explicit, MongoDB added deleteOne() and deleteMany(). In general, these approaches are favoured for novel applications.

db.collection.deleteOne() Deleting one collection in MongoDB In MongoDB 3.2.x, deleteOne() was added to the CRUD API for better operation semantics. One document matching the filter is deleted by this approach. A filter document is its argument.

Syntax:

db.collection.deleteOne(filter, options)

Code Example:

Delete one product with “Mouse” as the name:

db.products.deleteOne({ "name": "Mouse" });
  1. db.collection.deleteMany(): All documents that match the supplied filter are removed using this function.
  2. To get rid of every document in a collection, you can alternatively use deleteMany({}).

Syntax:

db.collection.deleteMany(filter, options)

Code Example:

db.products.insertMany([
    { "_id": 1, "name": "Laptop", "category": "Electronics", "price": 1200, "inStock": true },
    { "_id": 2, "name": "Keyboard", "category": "Electronics", "price": 75, "inStock": true },
    { "_id": 3, "name": "Mouse", "category": "Electronics", "price": 30, "inStock": false },
    { "_id": 4, "name": "Desk Chair", "category": "Furniture", "price": 150, "inStock": true },
    { "_id": 5, "name": "Monitor", "category": "Electronics", "price": 300, "inStock": true },
    { "_id": 6, "name": "Bookcase", "category": "Furniture", "price": 100, "inStock": false },
    { "_id": 7, "name": "Webcam", "category": "Electronics", "price": 50, "inStock": true }
]);

Delete all products that are out of stock (inStock: false):

db.products.deleteMany({ "inStock": false });

Delete all products in the ‘Furniture’ category:

db.products.deleteMany({ "category": "Furniture" });

Delete all documents from the collection (use with extreme caution!):

db.products.deleteMany({});

Atomicity of Document Deletions

The alteration of a single document is always atomic, even if it modifies many embedded documents. If a write action (including deletes) updates many documents, it is not atomic and may interleave.

Deleting Collections in MongoDB

The db.collection.drop() method deletes a collection and its indexes.

MongoDB Drop Collection The drop() method deletes a database collection, including its documents and indexes. Drop() eliminates indexes, making it more efficient than remove() without criteria for clearing all documents from a collection. The method returns true if the collection is dropped, false otherwise. If needed, recreate indexes on the empty collection after dropping.

Syntax:

db.collection.drop()

Code Example:

Drop the products_backup collection:

db.products_backup.drop();

Remove() Method – db.Collection.remove() The remove() method deletes documents from a collection. It allows optional deletion criteria to choose documents. Passing an empty document ({}) or no arguments will remove all documents from the collection. Setting justOne to true or 1 limits the process to deleting one document. The remove(), like SQL’s DELETE function, deletes documents within a collection but not the collection.

Syntax:

db.collection.remove(query, justOne)

Code Example:

// This method is deprecated. For demonstration purposes only:
db.products.remove({ "price": { "$lt": 40 } }); // Remove all products with price less than 40

Deleting Databases in MongoDB

To delete a database, its collections, and their data, call db.dropDatabase().

  • db.dropDatabase(): Databases are dropped using db.dropDatabase(). The specified database is deleted when run. The default test database will be deleted if you haven’t specifically chosen a database using the use command.
  • A document verifying the operation is returned by the command, such as {“dropped”: “mydb”, “ok”: 1}.
  • Critical Warning: db.dropDatabase() deletes files from disc and cannot be undone. Using this command requires considerable caution.

MongoDB’s data deletion instructions range from granular document updates using $pop and $pull to wholesale deletion of collections or databases. Because these operations are irreversible, always clarify your intent before using them, especially drop() and dropDatabase().

Index