MongoDB Delete Documents
In the previous chapters, we have learned how to add data to and update data in MongoDB collections. In this chapter, we will continue to learn about deleting MongoDB collections.
Common document deletion methods include deleteOne(), deleteMany(), and findOneAndDelete().
Use cases:
- Data cleaning: Delete old data or invalid data that is no longer needed.
- Data correction: Delete erroneous or duplicate documents during data correction.
- Automated tasks: Delete documents based on specific conditions in automated scripts or tasks.
1、deleteOne()
The deleteOne() method is used to delete a single document that matches the filter.
Syntax:
db.collection.deleteOne(filter, options)
- filter: The query criteria used to find the document to delete.
- options: (Optional) An optional parameter object.
Example
Returned result:
{
"acknowledged": true,
"deletedCount": 1
}
2、deleteMany()
The deleteMany() method is used to delete all documents that match the filter.
Syntax:
db.collection.deleteMany(filter, options)
- filter: The query criteria used to find the documents to delete.
- options: (Optional) An optional parameter object.
Example
Returned result:
{
"acknowledged": true,
"deletedCount": 1
}
3、findOneAndDelete()
The findOneAndDelete() method is used to find and delete a single document, and can optionally return the deleted document.
Syntax:
db.collection.findOneAndDelete(filter, options)
- filter: The query criteria used to find the document to delete.
- options: Optional parameter object, such as
projection、sortetc.
Example
{ name: "Charlie" },
{ projection: { name: 1, age: 1 } }
);
findOneAndDelete returns the deleted document; if no matching document is found, it returns null.
Options for Delete Operations
The options parameter of these deletion methods can usually include the following options:
- writeConcern: Specifies the acknowledgment level for the write operation.
- collation: Specifies the collation to use when comparing strings.
- projection(Only applicable to
findOneAndDelete): Specifies the fields to return. - sort(Only applicable to
findOneAndDelete): Specifies the sort order to determine which document to delete.
Example
Delete a single document:
db.myCollection.deleteOne({ name: "Alice" });
Delete multiple documents:
db.myCollection.deleteMany({ status: "inactive" });
Find and delete a single document:
db.myCollection.findOneAndDelete(
{ name: "Charlie" },
{ projection: { name: 1, age: 1 } }
);
Other extensions