Tuesday, January 27, 2015

How to autoincrement id at every insert in Pymongo?

Use a separate counters collection to track the last number sequence used. The _id field contains the sequence name and the seq field contains the last value of the sequence.

1- Insert into the counters collection, the initial value for the userid:
 db.orgid_counter.insert({'_id': "userid", 'seq': 0})  

2- Create a getNextSequence function in target language(I am using python) that accepts a name of the sequence. The function uses the find_And_Modify() method to atomically increment the seq value and return the new value:
 def getNextSequence(collection,name):  
   return collection.find_and_modify(query= { '_id': name },update= { '$inc': {'seq': 1}}, new=True ).get('seq');  

3-Use this getNextSequence() function during insert() and insert new user with new generated id .


  db.users.insert({'_uid': getNextSequence(db.orgid_counter,"userid"), 'name': "Sara a"})  

You can verify the results with find():
 db.users.find()  

No comments:

Post a Comment