MongoDB Delete Documents
In the previous chapters, we learned how to add data to and update data in MongoDB collections. In this chapter, we will continue to learn about deleting MongoDB collections.
Commonly used document deletion methods include deleteOne(), deleteMany(), and findOneAndDelete().
Use cases:
- Data Cleanup: delete old or invalid data that is no longer needed.
- Data correction: delete erroneous or duplicate documents during data correction.
- Automation 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 condition used to find the document to delete.
- options(optional): an optional parameter object.
Example
db.
myCollection
.
deleteOne
(
{
name
:
"Alice"
}
)
;
Return 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 condition used to find the document to delete.
- options(optional): an optional parameter object.
Example
db.
myCollection
.
deleteMany
(
{
status
:
"inactive"
}
)
;
Return 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 condition used to find the document to delete.
- options: optional parameter object, such as
projection、sort, etc.
Example
db.
myCollection
.
findOneAndDelete
(
{
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 delete methods can usually include the following options:
- writeConcern: specifies the acknowledgment level of write operations.
- collation: specifies the collation used 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 } }
);