govin
govin

Reputation: 6733

rowversion or doc version in mongodb

What would be a sound way to do row versioning in mongodb. Sql server had a rowversion field that got automatically incremented when a row got updated based on a relative time sql server tracked within the database. Wondering what a good scheme in mongo for the same would look like?

Upvotes: 2

Views: 1618

Answers (1)

david.storch
david.storch

Reputation: 691

There is no builtin support for row versioning in MongoDB such as the kind you mention for SQL server.

However, you could always add a version field to your documents. Then, whenever you wanted to update the document you would use the findAndModify command to do so atomically. Each such atomic update would also have to increment the document version number. For example, suppose the collection foo contained the document { "_id" : "example", "a" : 3, "version" : 1 }. The following atomically sets a field to 9 and increments the version number using the mongo shell:

db.foo.findAndModify({
  query: {_id: "example"},
  update: {$set: {a: 9}, $inc: {version: 1}}
});

By default, the document returned is the state of the document before the update was applied. To return the modified version of the document, add new: true to the query.

Note that if you do not need a copy of the modified document, then you can simply use update instead of findAndModify (i.e. findAndModify is good for updating and returning a document in one atomic step, otherwise update is just as good).

Upvotes: 1

Related Questions