How to autoincrement id at every insert in Pymongo?

11,552

It doesn’t seem like a very good idea, but if you really want to go through with it you can try setup like below.

It should work good enough in a low traffic application with single server, but I wouldn't try anything like this with replicated or sharded enviroment or if you perform large amount of inserts.

Create separate collection to handle id seqs:

db.seqs.insert({
    'collection' : 'admin_collection',
    'id' : 0
})

Whenever you need to insert new document use something similar to this:

def insert_doc(doc):
    doc['_id'] = str(db.seqs.find_and_modify(
        query={ 'collection' : 'admin_collection' },
        update={'$inc': {'id': 1}},
        fields={'id': 1, '_id': 0},
        new=True 
    ).get('id'))

    try:
        db.admin_collection.insert(doc)

    except pymongo.errors.DuplicateKeyError as e:
        insert_doc(doc)
Share:
11,552
Shivamshaz
Author by

Shivamshaz

Updated on July 09, 2022

Comments

  • Shivamshaz
    Shivamshaz almost 2 years

    I am using pymongo to insert documents in the mongodb. here is code for router.py file

        temp = db.admin_collection.find().sort( [("_id", -1)] ).limit(1)
        for doc in temp:
            admin_id = str(int(doc['_id']) + 1)
    
    
        admin_doc ={
        '_id'       :   admin_id,
        'question'  :   ques,
        'answer'    :   ans,
        }
        collection.insert(admin_doc)
    

    what should i do so that at every insert _id is incremented by 1.

  • Mr.Tiffenbox
    Mr.Tiffenbox over 4 years
    thanks for an effort like this @RMcG. i really appreciate for ur optional approach
  • Admin
    Admin over 2 years
    Your answer could be improved with additional supporting information. Please edit to add further details, such as citations or documentation, so that others can confirm that your answer is correct. You can find more information on how to write good answers in the help center.