Tuesday, 31 December 2013

Sequence numbers from pymongo

I was looking for a way to generate in a multi process environment unique sequence numbers.  My development language was python and the underlying database was MongoDB.  I found a fairly simple way to do this in MongoDB.

def getNextEventSeq(idkey):

   nextId = seqtab.find_and_modify(query={'_id':idkey}, 

                                   update = {'$inc' : {'seq':1}},

   return nextId['seq']        

MongoDB guarantees that find_and_modify() is atomic even across multiple mongos hence this is guaranteed to be threadsafe.

Here is the detailed article on MongoDB website


No comments:

Post a Comment