How to make an integer Id generator?

c#, mongodb

Solution

Its not good practice to make auto increment Id in MongoDB, as I will hurt in scaling your server, but If you want to make auto increment value it is not advisable to iterate your collection, Instead make a separate table (sequence like concept) and read value from there and increment it using findAndModify. It will be unique per 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:o.c, stuff:"abc"});

> o = db.counters.findAndModify(
...        {query: {_id: "userId"}, update: {$inc: {c: 1}}});
{ "_id" : "userId", "c" : 1 }
> db.mycollection.insert({_id:o.c, stuff:"another one"});

Problem

As it known, mongoDb default driver doesn't support automatic integer Id generation. I spent 2 days for thinking how to implement my own id generator of unique integer values. So, how to make it ?

Original source