How to Delete Single Document in MongoDB Collection Examples
Let’s look at some examples, that explains how users can delete a single document from a collection in MongoDB. We will cover different use cases of deleteOne method to delete single document from a collection.
In the following examples, we are working with:
Database: w3wiki Collection: contributor Document: four documents that contain the details of the contributors in the form of field-value pairs.
Deleting the First Document from Collection Example
In this example, we are deleting first document from the contributor collection.
db.contributor.deleteOne({})
Deleting a Single Document That Matches the Filter Example
In this example, we are deleting a single document that matches the filter, i.e., name: “Somya” from the contributor collection.
Delete Single Document When Multiple Document Match Filter Example
In this example, we are deleting a document from the contributor collection. Here two document matches the filter(i.e., language: “C#”), so this method will delete the first document that matches the filter among these two documents.
Delete Single Document in MongoDB Using MongoShell
deleteOne method is used to delete a single document in MongoDB. This method deletes a single existing document from the collection that matches the specified filter. This method can be used in multi-document transactions.
It deletes the first document that matches the condition if multiple documents satisfy the condition.
Note: MongoDB deleteOne method throws an exception when used in a capped collection.
Syntax
db.collection.deleteOne(
<filter>,
{
writeConcern: <document>,
collation: <document>,
hint: <document|string> // Available starting in MongoDB 4.4
}
)
Parameters:
filter: It specifies the selection criteria for the delete using query operators. If it contains empty document, i.e, {}, then this method will delete the first document from the collection.
Optional Parameters:
- writeConcern: It is only used when you do not want to use the default write concern. The type of this parameter is document.
- collation: It specifies the use of the collation for operations. It allows users to specify the language-specific rules for string comparison like rules for lettercase and accent marks. The type of this parameter is document.
- hint: It specifies the index to use to support the filter query
Return:
This method will return a document that contains a boolean acknowledged as true (if the write concern is enabled) or false (if the write concern is disabled) and deletedCount that represents the total number of deleted documents.