Introduction to MongoDB collection.findAndModify() Method
findAndModify()
is a collection operation method in MongoDB that allows users to return the document before the update when performing an update operation. This method is widely used in scenarios where the document needs to be manipulated before the update is executed.
Syntax
The syntax of the findAndModify()
method is as follows:
db.collection.findAndModify({
query: <document>,
sort: <document>,
remove: <boolean>,
update: <document>,
new: <boolean>,
fields: <document>,
upsert: <boolean>
})
Use Cases
The findAndModify()
method is useful in scenarios where a document needs to be updated and returned before the update, such as when obtaining the automatic numbering value of a document before updating.
Examples
Here are two complete examples of using the findAndModify()
method.
Example 1
First, we create a collection called users
and insert some data into it.
> db.users.insertMany([{name: 'Alice', age: 25}, {name: 'Bob', age: 30}, {name: 'Charlie', age: 35}])
Then, we use the findAndModify()
method to update a document in the users
collection and return the document before the update.
> db.users.findAndModify({
query: {name: 'Bob'},
update: {$set: {age: 31}},
new: true
})
In the above example, we use the query
parameter to specify the document to be updated, use the update
parameter to set the field to be updated, and use the new
parameter to specify that the updated document should be returned.
Example 2
We can also use the findAndModify()
method to delete a document and return the document before deletion.
First, we create a collection called messages
and insert some data into it.
> db.messages.insertMany([
{from: 'Alice', to: 'Bob', content: 'Hello'},
{from: 'Bob', to: 'Alice', content: 'Hi'}
])
Then, we use the findAndModify()
method to delete a document in the messages
collection and return the document before deletion.
> db.messages.findAndModify({
query: {from: 'Alice'},
remove: true
})
In the above example, we use the query
parameter to specify the document to be deleted and use the remove
parameter to specify that the document should be deleted. Since we did not specify the new
parameter, the updated document is not returned by default.
Conclusion
The findAndModify()
method is one of the commonly used collection operation methods in MongoDB, which can return the document before the update when updating a document. This method is very useful in scenarios where the document needs to be manipulated before the update.