Introduction to MongoDB collection.findOneAndDelete() Method
In MongoDB, findOneAndDelete()
is a method used to find and delete a single document. The feature of this method is that it can execute both finding and deleting in a single atomic operation, which is very convenient.
Syntax
The syntax of findOneAndDelete()
is as follows:
db.collection.findOneAndDelete(filter, options)
Where filter
is a query condition used to match the document to be deleted, and options
is an optional parameter object used to specify other options, such as sorting, projection, etc.
Use cases
findOneAndDelete()
method is usually used in the following scenarios:
- Delete a single document in the collection and return the contents of the document;
- Only delete a part of the document, not the whole document;
- Execute an atomic operation to avoid concurrency issues.
Examples
Here are two examples of using the findOneAndDelete()
method.
Example 1
First, we create a collection named users
and insert two documents into it:
db.users.insertMany([
{ name: "Alice", age: 25 },
{ name: "Bob", age: 30 }
])
Now we use the findOneAndDelete()
method to delete the document with the age
field equal to 30
and return the contents of the document:
var result = db.users.findOneAndDelete({ age: 30 })
printjson(result)
The result is as follows:
{ "_id" : ObjectId("615d0a88808d2c77123d3a23"), "name" : "Bob", "age" : 30 }
As you can see, the contents of the deleted document are returned.
Example 2
We then use a scenario with concurrency issues to demonstrate the effect of the findOneAndDelete()
method. Suppose we have a collection named inventory
that stores inventory information for several products.
db.inventory.insertMany([
{ _id: 1, item: "apple", qty: 5 },
{ _id: 2, item: "banana", qty: 10 },
{ _id: 3, item: "orange", qty: 15 }
])
Now two users are trying to buy the apple
product at the same time, and they both perform the following operation:
var result = db.inventory.findOneAndDelete({ item: "apple" })
printjson(result)
According to MongoDB’s default behavior, if two users perform the above operation at the same time, only one user will succeed in purchasing, and the other user will get null
as the result. This is because the user who performs the operation first reduces the inventory quantity of the apple
product by 1
, and the second user finds that the inventory has already been reduced to 4
when performing the operation and cannot reduce it again.
Conclusion
The findOneAndDelete()
method is a very convenient method in MongoDB to find and delete a single document. It can avoid concurrency issues and can execute both finding and deleting in a single atomic operation, which is very convenient.