Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to make an integer Id generator?

Tags:

c#

mongodb

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 ?

like image 892
Tim Gim Avatar asked Jun 15 '12 10:06

Tim Gim


People also ask

How do you create a unique identifier?

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.

What is generated ID?

The System Generated User ID functionality enables the system to automatically generate a unique ID for users who are created within the system.

What is a hash of ids?

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.


2 Answers

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"});
like image 107
maaz Avatar answered Sep 30 '22 14:09

maaz


I would use a GUID as primary key instead of an integer. It has mainly two benefits

  • It is thread safe
  • You don't need to worry about calculating next ID.
  • 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.

like image 38
Oscar Foley Avatar answered Sep 30 '22 14:09

Oscar Foley