Fix This Page
Navigation

Update Document if Current

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.

var myDocument = db.products.findOne( { sku: "abc123" } );

if ( myDocument ) {
   var oldQuantity = myDocument.quantity;
   var oldReordered = myDocument.reordered;

   var results = db.products.update(
      {
        _id: myDocument._id,
        quantity: oldQuantity,
        reordered: oldReordered
      },
      {
        $inc: { quantity: 50 },
        $set: { reordered: true }
      }
   )

   if ( results.hasWriteError() ) {
      print( "unexpected error updating document: " + tojson(results) );
   }
   else if ( results.nMatched === 0 ) {
      print( "No matching document for " +
             "{ _id: "+ myDocument._id.toString() +
             ", quantity: " + oldQuantity +
             ", reordered: " + oldReordered
             + " } "
      );
   }
}

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.