MongoDB Auto-Increment

MongoDB does not have an auto-increment feature like SQL does. MongoDB's _id is a 12-byte unique identifier automatically generated by the system.

But in some cases, we may need to implement auto-increment functionality for ObjectId.

Since MongoDB does not implement this feature, we can do it programmatically. Below, we will implement auto-increment for the _id field in the counters collection.


Use counters collection

Consider the following products document. We want the _id field to have auto-increment functionality from 1, 2, 3, 4 to n.

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

To do this, create a counters collection. The sequence field value can auto-increment:

>db.createCollection("counters")

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

{
  "_id":"productid",
  "sequence_value": 0
}

The sequence_value field is the value after the sequence has been auto-incremented.

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

>db.counters.insert({_id:"productid",sequence_value:0})

Create JavaScript function

Now, we create a function getNextSequenceValue that takes the sequence name as input. The specified sequence will auto-increment by 1 and return the latest sequence value. In this example, the sequence name is productid.

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

Use JavaScript function

Next, we will use the getNextSequenceValue function to create a new document and set the document's _id to the returned sequence value automatically:

>db.products.insert({
   "_id":getNextSequenceValue("productid"),
   "product_name":"Apple iPhone",
   "category":"mobiles"})

>db.products.insert({
   "_id":getNextSequenceValue("productid"),
   "product_name":"Samsung S3",
   "category":"mobiles"})

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

To verify whether the function works, we can read the document using the following command:

>db.products.find()

The above command will return the following result. We can see that the _id field is auto-incrementing:

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

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