0

Does Mongo automatically track a version which is incremented for each update and can be used for optimistic locking?

So something that would correspond to functionality described here in ElasticSearch http://www.elasticsearch.org/blog/elasticsearch-versioning-support/

brent
  • 1,095
  • 1
  • 11
  • 27
  • Have you seen http://stackoverflow.com/questions/4185105/ways-to-implement-data-versioning-in-mongodb ? – xlembouras Feb 26 '14 at 21:52
  • Yup, I had come across it. Seems to be discussing how to implement a "history" on a object, and some of the solutions discussed do touch on a basic version number, which are supplied in various libraries, not as out the box Mongo functionality. So I wanted to ask the question to check I wasn't missing out the box functionality that could be leveraged (and is hard to find via googling) – brent Feb 26 '14 at 22:03

1 Answers1

0

No, MongoDB does not store versions of documents. There is only the "current" version of the document as far as the database API is concerned.

It would be necessary to create your own scheme if you wanted such a thing. You could use a version field in your document and use $inc for example to increment it as needed and also verify that the version value matched before applying an update.

Example:

db.myCollection.update( 
      { _id: "abc123", _version: 5 }, 
      { 
         $set: { 'fieldA' : 'some-value' }, 
         $inc: { '_version' : 1 }
      }
)

The above example would find a document with the specific _id and _version fields. If matched, a field called fieldA is set to a new value and the _version field is incremented by 1. If another update was attempted on the same document and version, it would fail as the _version would have been updated to 6.

WiredPrairie
  • 58,954
  • 17
  • 116
  • 143