MongoDB Delte Documents Tutorial

The MongoDB deleteOne() and deleteMany()methods are used to remove documents from a collection.

Delete a Single Document

We use deleteOne() to remove a single document that matches a specific filter.

db.myCollection.deleteMany({ age: { $lt: 25 } });
        

Delete Multiple Documents

The deleteMany() is to remove multiple documents that match a specific filter.

db.myCollection.deleteMany({ age: { $lt: 25 } });        

Delete All Documents

To delete all documents in a collection, you can use an empty filter with deleteMany().

db.myCollection.deleteMany({});
        

Result of Delete Operations

Both deleteOne() and deleteMany() return a result object with information about the operation

const result = db.myCollection.deleteOne({ name: "John" });
printjson(result);
          

Delete with Collation

You can specify collation to perform case-insensitive deletions.

db.myCollection.deleteOne({ name: "jane" }, { collation: { locale: "en", strength: 2 } });
        

Delete with Write Concern

Specify write concern options for safe deletes, such as { w: "majority" }.

db.myCollection.deleteOne({ name: "Mark" }, { writeConcern: { w: "majority" } });
        

Deleting Documents by _id

You can delete documents based on their unique _id value.

db.myCollection.deleteOne({ _id: ObjectId("document_id_here") });
        

Conditional Deletes

You can perform conditional deletes with operators like $eq, $gt, and $lt.

db.myCollection.deleteMany({ age: { $lt: 25 } });
        

Deleting Nested Documents

To delete specific elements within nested arrays, use the $pull operator with an update operation.