Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Auto increment in MongoDB to store sequence of Unique User ID

I am making a analytics system, the API call would provide a Unique User ID, but it's not in sequence and too sparse.

I need to give each Unique User ID an auto increment id to mark a analytics datapoint in a bitarray/bitset. So the first user encounters would corresponding to the first bit of the bitarray, second user would be the second bit in the bitarray, etc.

So is there a solid and fast way to generate incremental Unique User IDs in MongoDB?

like image 712
est Avatar asked Dec 05 '11 10:12

est


People also ask

Can you auto-increment in MongoDB?

Although MongoDB does not support auto-increment sequence as a default feature like some relational databases, we can still achieve this functionality using a counter collection. The counter collection will have a single document that tracks the current unique identifier value.

Does MongoDB generate ID automatically?

By default, MongoDB generates a unique ObjectID identifier that is assigned to the _id field in a new document before writing that document to the database. In many cases the default unique identifiers assigned by MongoDB will meet application requirements.

How do I increment a variable in MongoDB?

In MongoDB, the $inc operator is used to increment the value of a field by a specified amount. The $inc operator adds as a new field when the specified field does not exist, and sets the field to the specified amount. The $inc accepts positive and negative value as an incremental amount.

Should I use auto-increment ID?

Auto-increment should be used as a unique key when no unique key already exists about the items you are modelling. So for Elements you could use the Atomic Number or Books the ISBN number.


2 Answers

As selected answer says you can use findAndModify to generate sequential IDs.

But I strongly disagree with opinion that you should not do that. It all depends on your business needs. Having 12-byte ID may be very resource consuming and cause significant scalability issues in future.

I have detailed answer here.

like image 159
expert Avatar answered Oct 14 '22 18:10

expert


You can, but you should not https://web.archive.org/web/20151009224806/http://docs.mongodb.org/manual/tutorial/create-an-auto-incrementing-field/

Each object in mongo already has an id, and they are sortable in insertion order. What is wrong with getting collection of user objects, iterating over it and use this as incremented ID? Er go for kind of map-reduce job entirely

like image 27
Konstantin Pribluda Avatar answered Oct 14 '22 17:10

Konstantin Pribluda