Implementing atomic counters in Mongo
Atomic counters are a necessity for a large number of use cases. Mongo doesn't have a built in feature for atomic counters; nevertheless, it can be easily implemented using some of its cool offerings. In fact, with the help of previously described findAndModify()
command, implementing is quite simple. Refer to the previous recipe Atomic find and modify operations to know what atomic find and modify operations are in Mongo.
Getting ready
Look at the recipe Installing single node MongoDB in Chapter 1, Installing and Starting the Server and start a single instance of Mongo. That is the only prerequisite for this recipe. Start a mongo shell and connect to the started server.
How to do it…
Execute the following piece of code from the mongo shell:
> function getNextSequence(counterId) { return db.counters.findAndModify( { query: {_id : counterId}, update: {$inc : {count : 1}}, upsert: true, fields:{count:1, _id:0}, new: true...