Auto increment in MongoDB to store sequence of Unique User ID

mongodb auto increment id nodejs
mongodb auto increment id c#
mongodb auto increment id python
auto increment id in mongodb from node js
mongodb auto increment id spring boot
auto increment in mongodb spring boot
auto increment in mongodb node js mongoose
mongodb sequence generator java

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?

You can, but you should not

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

Auto increment in MongoDB to store sequence of Unique User ID?, To auto increment in MongoDB to store a sequence of unique user id, let us create a collection which contains information about last sequence  To auto increment in MongoDB to store a sequence of unique user id, let us create a collection which contains information about last sequence values of all documents. Let us first create a collection. Now, we will create a function that will generate an auto increment in MongoDB to store sequence.

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.

MongoDB - Auto-Increment Sequence, MongoDB - Auto-Increment Sequence. MongoDB does not have out-of-the-box auto-increment functionality, like SQL databases. By default, it uses the 12-byte ObjectId for the _id field as the primary key to uniquely identify the documents. The database sequence is a database product that creates unique values by getting an auto increment with a value which could be of a step of 1, 2, and so on. This sequence is very important as if a transaction id is associated with a sequence then the associated incremented number with the sequence will always be unique and never overlap.

I know this is an old question, but I shall post my answer for posterity...

It depends on the system that you are building and the particular business rules in place.

I am building a moderate to large scale CRM in MongoDb, C# (Backend API), and Angular (Frontend web app) and found ObjectId utterly terrible for use in Angular Routing for selecting particular entities. Same with API Controller routing.

The suggestion above worked perfectly for my project.

 "name":"John Doe",

The reason it is perfect for my case, but not all cases is that as the above comment states, if you delete 3 records from the collection, you will get collisions.

My business rules state that due to our in house SLA's, we are not allowed to delete correspondence data or clients records for longer than the potential lifespan of the application I'm writing, and therefor, I simply mark records with an enum "Status" which is either "Active" or "Deleted". You can delete something from the UI, and it will say "Contact has been deleted" but all the application has done is change the status of the contact to "Deleted" and when the app calls the respository for a list of contacts, I filter out deleted records before pushing the data to the client app.

Therefore, db.collection.find().count() + 1 is a perfect solution for me...

It won't work for everyone, but if you will not be deleting data, it works fine.

Generate MongoDB Auto Increment Sequence - In 7 Steps, Let's use the following steps to generate the MongoDB auto increment sequence for the item id: Generate sample collection. Insert a document into a collection. Insert the record into a collection. Database sequence. Create a JavaScript function. Use JavaScript function. View inserted a record from store collection. Auto incrementing IDs for MongoDB. If you’re familiar with relational databases like MySQL or PostgreSQL, you’re probably also familiar with auto incrementing IDs. You select a primary key for a table and make it auto incrementing. Every row you insert afterwards, each of them gets a new ID, automatically incremented from the last one.

First Record should be add

"_id" = 1    in your db

$database = "demo";
$collections ="democollaction";
echo getnextid($database,$collections);

function getnextid($database,$collections){

     $m = new MongoClient();
    $db = $m->selectDB($database);
    $cursor = $collection->find()->sort(array("_id" => -1))->limit(1);
    $array = iterator_to_array($cursor);

    foreach($array as $value){

        return $value["_id"] + 1;


Learn How MongoDB Auto Increment Sequence Works, Learn How To Auto-Increment Sequences in MongoDB integer sequence that starts from 1, 2, 3, and so on as the item id of an item store. MongoDB does not have out-of-the-box auto-increment functionality, like SQL databases. By default, it uses the 12-byte ObjectId for the _id field as the primary key to uniquely identify the documents. However, there may be scenarios where we may want the _id field to have some auto-incremented value other than the ObjectId.

The best way I found to make this to my purpose was to increment from the max value you have in the field and for that, I used the following syntax:

maxObj = db.CollectionName.aggregate([
    $group : { _id: '$item', maxValue: { $max: '$fieldName' } } 
fieldNextValue = maxObj.maxValue + 1;

$fieldName is the name of your field, but without the $ sign.

CollectionName is the name of your collection.

The reason I am not using count() is that the produced value could meet an existing value.

The creation of an enforcing unique index could make it safer:

db.CollectionName.createIndex( { "fieldName": 1 }, { unique: true } )

Auto incrementing IDs for MongoDB – Polyglot.Ninja(), You select a primary key for a table and make it auto incrementing. It's true that you can insert anything unique as the required _id field of a mongodb Each document in this sequences collection will hold the last used ID for a other forums, people have scaled this to thousands and millions of users. In this tutorial, we are going to learn how to implement a sequential and auto-generated field for MongoDB in Spring Boot. If you are new to MongoDB and Spring then visit Spring Data MongoDB Tutorial. Understanding step by step today about "Auto-Generated Field for MongoDB using Spring Boot" [update] Updated new errors in this article.

MongoDB Create an Auto-Increment Sequence Field, By default mongoDB uses standard auto generated ObjectId to Login · Registration we will create auto incrementing sequence to maintain the unique roll switched to db technicalkeeda; > db.studentcounters.insert(  The simple use case is that to store an employee in MongoDB via Waterline ( blueprint APIs ). Let the _id be continue to be Object_ID ( yes Unique Index / Primary Key ) for Mongo DB. But the employee_number should be whole number , lets say 100 to 1000 and more..

Generating Globally Unique Identifiers for Use with MongoDB , By default, MongoDB generates a unique identifier that is assigned to the _id field ObjectID is automatically generated by the database drivers, and will be similar to the sequence functionality that is implemented by some RDBMSs. field will be incremented atomically with the fetch of this document", }. Autoincrement in MongoDB MongoDB also supports auto-increment like SQL database. Basically, mongodb provides ObjectId for 12-byte. But we can also make it custom.

Auto Increment Sequence in MongoDB, MongoDB does provide the ObjectId, which can be used as a primary key– a value that makes each document unique within a collection. Creating Unique Key in MySQL table referring to date? Check a column for unique value in MySQL; How to select unique value in MySQL? How to return only unique values (no duplicates) in MongoDB? Auto increment in MongoDB to store sequence of Unique User ID? How to create unique index in Android sqlite? How to use UNIQUE constraints in Android

  • I meet the same problem like yours, how to generate id to set bitset position. Did you solve this problem?
  • Hope this can help you…
  • May be this can help you:…
  • The problem is concurrenty. iterate would emit duplicate incremental ID.
  • You need this ID only for analysis, not data storage. IIUC, you need sequential ID only as index for your array, so you can build bitset. You can achieve it without storing this incremental ID in database, and you can build your bit-array without retrieving data to client
  • It's quite unwise to get incr ID by iteration everytime, especially you are dealing with millions of users per datapoint. Dong a MAU would require like 30x iterations.
  • It's unwise to use incremental sequences when you have millions of users in the first place. However, millions of users doesn't exactly play well with bit arrays either, does it? I find it hard to tell what exactly you're trying to achieve. Concurrency will not be a problem using findAndModify. Also see and the HiLo Algorithm:
  • I just want to store some Redis bitmap data in Mongo… for later queries.
  • You can if you want to, I disagree too, because that's a mongo inbuilt feature to .createIndex ( { "number" : 1 }, { unique : true } ) where the one represents increment and -1 otherwise
  • is there any special reason that the mongodb states that you have to use a function and a counters sequence, instead of your soultion as does maybe transcation processing messing things? do your solution works well in web server environment cruds' ? thank you for your answer
  • This would not be good in a concurrent setup. You could easily get documents with the same _id if they did the count at the same time.
  • absolutely! In my instance, I am not having to deal with concurrency or sharding at all so I don't have any problems using a find().Count()+1 As in my original answer, this won't work for everyone in every situation, but it has definitely has worked in my particular scenario. App has been in production now for nearly 12 months with no issues regarding my incrementing id's.
  • This solution is bad, because you changed the history! In one time can be a document with id 3 and another time it can happen again. But there is not any relation between the documents that has this id's