findAndModify() - Find and update documents command

Finds documents and updates them with new values.

Syntax diagram

Read syntax diagramSkip visual syntax diagramdb.collection. findAndModify(specification)

Command parameters

specification
This parameter specifies a JSON object with the following optional content:
query document
This parameter specifies a query object for filtering documents.
fields document
This parameter specifies a query object for selecting fields to return.
sort document
This parameter specifies a query object that defines the sort order to apply before it selects the first document.
remove true
This parameter specifies a query object that removes the document. When it is true, the selected document is removed. The default is false.
update document
This parameter specifies a query object that contains the update.
new (true | false)
If the value is true, this parameter returns the updated document instead of the original. If the value is false, the old document is returned (discarded except for use by time travel functionality).
insert (true | false)
If the value is true, this parameter inserts a new document, if the query does not return a document. If the value is false, this parameter updates the document or returns an error if the document is not present.
fullResponse (true | false)
If the value is true, the parameter returns the document or documents that are the result of the query. Also, a status object is returned that contains the write result and the last error. If the value is false, the parameter returns only the document.

Example

Find the first document with the name Joe and update the age field with the value 6:
db.mycollection.findAndModify({query : {name : "Joe"}, update : {$set : {age : 6}}})
Sample output is as follows:
{
"lastErrorObject":
{
"updatedExisting":true,
"n":1,
"err": null ,
"ok":1
},
"value":
{
"_id":{"$oid":"51cdc007927a75e5a8c327e3"},
"name":"Joe",
"age":5
}
}