MongoDB Auto-Increment Sequence

MongoDB does not have auto-Sequence capabilities like SQL, The _id of MongoDB is a 12-byte unique identifier Auto-Incrementally generated by the system.

But in some cases we may need to implement the ObjectId auto-increment feature.

Since MongoDB does not implement this function, we can do it programmatically. Below we will The counters collection implements the _id field to grow Auto-Incrementally.

Using counters collection

Consider the following products document. We want the _id field to achieve Auto-Sequence from 1,2,3,4 to n.

  "product_name": "Apple iPhone",
  "category": "mobiles"

To do this, create a counters collection, and the sequence field values can be Auto-Incrementally lengthened:


Now we insert the following documents into the counters collection, using productid as the key:

  "sequence_value": 0

sequence_value field is a value after the sequence has passed through auto-Sequence.

Use the following command to insert into the sequence document of the counters collection:


Creating Javascript functions

Now we create the function getNextSequenceValue as input for the sequence name, The specified sequence Auto-Incrementally increments by 1 and returns the latest sequence value. In this example the sequence is named productid .

>function getNextSequenceValue(sequenceName){
   var sequenceDocument = db.counters.findAndModify(
         query:{_id: sequenceName },
         update: {$inc:{sequence_value:1}},
   return sequenceDocument.sequence_value;

Using Javascript functions

Next we will create a new document using the getNextSequenceValue function, And set the document _id to the sequence value returned Auto-Incrementally:

   "product_name":"Apple iPhone",

   "product_name":"Samsung S3",

As you can see, we use the getNextSequenceValue function to set the _id field.

To verify that the function works, we can use the following command to read the document:


The above command will return the following results, we found that the _id field is self-incrementing:

{ "_id" : 1, "product_name" : "Apple iPhone", "category" : "mobiles"}

{ "_id" : 2, "product_name" : "Samsung S3", "category" : "mobiles" }

Welookups is optimized for learning. © 2018 -

All Right Reserved and you agree to have read and accepted our term and condition.