Itβs not a good practice to automatically increase Id in MongoDB, since I will be sick when scaling your server, but if you want to make the value of automatic increase, it is inappropriate to iterate your collection. Instead, make a separate table (sequence, for example) and read the value from there and increase it with findAndModify. It will be unique for each table.
> db.counters.insert({_id: "userId", c: 0}); > var o = db.counters.findAndModify( ... {query: {_id: "userId"}, update: {$inc: {c: 1}}}); { "_id" : "userId", "c" : 0 } > db.mycollection.insert({_id:oc, stuff:"abc"}); > o = db.counters.findAndModify( ... {query: {_id: "userId"}, update: {$inc: {c: 1}}}); { "_id" : "userId", "c" : 1 } > db.mycollection.insert({_id:oc, stuff:"another one"});
source share