📅  最后修改于: 2023-12-03 15:17:42.558000             🧑  作者: Mango
Mongo findOneAndUpdate is a MongoDB method that updates and returns a single document in a collection. It allows you to update a document in place, without needing to retrieve and manipulate it in your application code.
db.collection.findOneAndUpdate(filter, update, options)
filter
- A query that matches the document to updateupdate
- The update operations to apply to the documentoptions
- Optional settings for the update operationSuppose we have a collection users
that contains documents with the following structure:
{
"_id": ObjectId("6114e0920a7c392c4752501d"),
"username": "johndoe",
"age": 30,
"email": "johndoe@example.com"
}
If we want to increment the user's age by 1 and return the updated document, we can use the following findOneAndUpdate
query:
db.users.findOneAndUpdate(
{ username: "johndoe" },
{ $inc: { age: 1 } },
{ returnOriginal: false }
);
This will return the updated document:
{
"_id": ObjectId("6114e0920a7c392c4752501d"),
"username": "johndoe",
"age": 31,
"email": "johndoe@example.com"
}
Note that the returnOriginal: false
option is used to return the updated document instead of the old one.
Mongo findOneAndUpdate is a powerful method that allows you to update a document in place while retrieving the updated version in a single operation. By using this method, you can reduce the amount of data that needs to be transferred between your application code and the database server, improving performance and reducing latency.