- MongoDB CRUD Operations >
- MongoDB CRUD Tutorials >
- Update Document if Current
Update Document if Current¶
On this page
Overview¶
The Update if Current pattern is an approach to concurrency control when multiple applications have access to the data.
Pattern¶
The pattern queries for the document to update. Then, for each field to modify, the pattern includes the field and its value in the returned document in the query predicate for the update operation. This way, the update only modifies the document fields if the fields have not changed since the query.
Example¶
Consider the following example in the mongo
shell. The
example updates the quantity
and the reordered
fields of a
document only if the fields have not changed since the query.
Changed in version 2.6: The db.collection.update()
method now returns a
WriteResult()
object that contains the status of
the operation. Previous versions required an extra
db.getLastErrorObj()
method call.
Modifications to the Pattern¶
Another approach is to add a version
field to the documents.
Applications increment this field upon each update operation to the
documents. You must be able to ensure that all clients that connect
to your database include the version
field in the query predicate.
To associate increasing numbers with documents in a collection, you can
use one of the methods described in
Create an Auto-Incrementing Sequence Field.
For more approaches, see Concurrency Control.