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 ?
The simplest way to generate identifiers is by a serial number. A steadily increasing number that is assigned to whatever you need to identify next. This is the approached used in most internal databases as well as some commonly encountered public identifiers.
The System Generated User ID functionality enables the system to automatically generate a unique ID for users who are created within the system.
A transaction hash/id is a unique string of characters that is given to every transaction that is verified and added to the blockchain. In many cases, a transaction hash is needed in order to locate funds.
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"});
I would use a GUID as primary key instead of an integer. It has mainly two benefits
Code needed to get new ID is pretty easy
Guid.NewGuid()
Check this useful article in CodingHorror that explains pros and cons of using GUID over classical integer IDs.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With