📜  mongofindoneandupate (1)

📅  最后修改于: 2023-12-03 15:17:42.558000             🧑  作者: Mango

Mongo findOneAndUpdate

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.

Syntax
db.collection.findOneAndUpdate(filter, update, options)
Parameters
  • filter - A query that matches the document to update
  • update - The update operations to apply to the document
  • options - Optional settings for the update operation
Example

Suppose 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.

Conclusion

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.