findOneAndUpdate() - Update a single JSON document and return the updated JSON document command

Updates a single document based on the filter and sort criteria. Returns either the original document or the updated document, depending on the value of the new command parameter.

Syntax diagram

Read syntax diagramSkip visual syntax diagramdb.collection. findOneAndUpdate(spec)

Command parameters

spec
A JSON object with the following content:
query
An optional filter for selecting a subset of documents.
fields
Selects fields to either include or exclude.
  • Optional.
  • Possible values: 0 | 1.
  • 0 = exclude; 1 = include.
sort
An optional JSON object for specifying sort criteria.
update
An object containing the update operation to apply.
new
Specifies which version of a document to return.
  • Optional
  • Possible values: true | false.
  • Default value: false.
  • If the value is true, the parameter returns the updated document. If the value is false, the parameter returns the old version of the document.
upsert
Updates or inserts a missing document.
  • Optional.
  • Possible values: true | false.
  • Default value: false.
  • If the value is true, this optional parameter updates a document or inserts a missing document. If the value is false, the parameter updates only the document.
fullresponse
Returns lastError object and specified document.
  • Optional
  • Possible values: true | false.
  • Default value: false.
  • If the value is true, this parameter returns the lastError object and the specified document. If the value is false, only the document is returned.

Output

A JSON document that is deleted, based on the selected filtering.

Examples

The following example shows the command syntax for finding the first document in the collection excluding the abstract field. The command also requests that he author field in the document be updated to the value Mark Twain:
db.mycollection.findOneAndUpdate({
	update : { $set : { author : “Mark Twain” } },
	fields : { abstract : 0 }
})
The following example shows the command syntax for finding the first document with the name Joe in the collection mycollection. The command also requests that the age field be updated to a value of 6:
db.mycollection.findOneAndUpdate({
	query : { name : “Joe” },
	update : { $set : { age : 6 } }
})
The following example shows the output from the previous query:
{	
“_id”:{“$oid”:”51cdc007927a75e5a8c327e3”},
“name”:”Joe”,
“age”:5
}
The following example shows the command syntax for the previous query, but with the fullresponse parameter set to true:
db.mycollection.findOneAndUpdate({
	query : { name : “Joe” },
	update : { $set : { age : 6 } },
	fullresponse : true
})
The following example shows the output from the query with the fullresponse parameter set to true:
{
“lastErrorObject”:
{
“updatedExisting”:true,
“n”:1,
“err”: null,
“ok”:1
},
“value”:
{	
“_id”:{“$oid”:”51cdc007927a75e5a8c327e3”},
“name”:”Joe”,
“age”:5
}
}