Delete Document:

In MongoDB shell, you can use the deleteOne() and deleteMany() methods to remove documents from a collection. These methods allow you to delete either a single document or multiple documents that match a specified criteria. Let's go through each method and their usage:


deleteOne() method:

The deleteOne() method removes a single document that matches the specified criteria from a collection.

Syntax:

db.collectionName.deleteOne(filter)

collectionName :is the name of the collection you want to delete the document from.

filter :is a document that specifies the criteria for matching the document to be deleted.

Example:

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

This query deletes the document with the _id value of "12345" from the "myCollection" collection. Only the first document that matches the criteria will be deleted.


deleteMany() method:

The deleteMany() method removes multiple documents that match the specified criteria from a collection.

Syntax:

db.collectionName.deleteMany(filter)

collectionName :is the name of the collection you want to delete the documents from.

filter :is a document that specifies the criteria for matching the documents to be deleted.

Example:

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

This query deletes all documents in the "myCollection" collection where the "age" field is greater than 25. It removes multiple documents that match the criteria.


It's important to note that the deleteOne() and deleteMany() methods permanently remove the documents from the collection. Be cautious while using these methods as the deleted data cannot be easily recovered.


These methods provide a simple and effective way to delete documents in MongoDB shell based on your specific criteria, whether you want to remove a single document or multiple documents from a collection