Database Reference
In-Depth Information
Modifying a Document Atomically
You can use the
find_and_modify()
function to modify a document atomically and return the results. The
find_and_modify()
function can be used to update only a single document—and nothing more. You should also
keep in mind that the document returned will not by default include the modifications made; getting this information
requires that you specify an additional argument,
new: True
.
The
find_and_modify()
function can be used with multiple parameters, and you must include either the
update
parameter or the
remove
parameter. The following list covers all the available parameters, explaining what they are
and what they do:
query
: Specifies a filter for the query. If this isn't specified, then all documents in the collection
will be seen as possible candidates, after which the first document it encounters will be
updated or removed.
•
update
: Specifies the information to update the document with. Note that any of the modifying
operators specified previously can be used for this.
•
upsert
: If set to
True
, performs an upsert.
•
sort
: Sorts the matching documents in a specified order.
•
full_response
: If set to
True
, returns the entire response object.
•
remove
: If set to
True
, removes the first matching document.
•
new
: If set to
True
, returns the updated document rather than the
selected
document. This is
not set by default, however, which might be a bit confusing sometimes.
•
fields
: Specifies the fields you would like to see returned, rather than the entire document.
This works identically to the
find()
function. Note that the
_id
field will always be returned
unless explicitly disabled.
•
Putting the Parameters to Work
You know what the parameters do; now it's time to use them in a real-world example in conjunction with the
find_and_modify()
function. Begin by using
find_and_modify()
to search for any document that has a key/value
pair of
"Type" : "Desktop"
—and then update each document that matches the query by setting an additional key/value
pair of
"Status" : "In repair"
. Finally, you want to ensure that MongoDB returns the updated document(s),
rather than the old document(s) matching the query:
>>> collection.find_and_modify(query={"Type" : "Desktop"},
... update={'$set' : {'Status' : 'In repair'} }, new=True )
{
u'ok': 1.0,
u'value': {
u'Status': u'In repair',
u'Tags': [u'Desktop', u'In use', u'Marketing', u'Warranty'],
u'ItemNumber': u'4532FOO',
u'Location': {
u'Department': u'Marketing',
u'Building': u'2B',
u'Owner': u'Martin, Lisa',
u'Desknumber': 131131
},