MongoDB - Auto Increment Sequence

MongoDB - Auto Increment Sequence

MongoDB does not have built-in auto-increment functionality like SQL databases do. By default, it uses the 12-byte ObjectId for the _id field as the primary key to uniquely identify documents. However, there may be scenarios where we may want the _id field to have some auto-increment value other than ObjectId.

Since this is not a default feature in MongoDB, we will programmatically achieve this functionality using a collection of counters as suggested in the MongoDB documentation.

Using a Collection of Counters

Consider the following product document . We want the _id field to be an auto- incrementing integer sequence starting from 1,2,3,4 to n.

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

To do this, create a counters collection that will keep track of the last value of the sequence for all fields in the sequence.

>db.createCollection("counters")

Now, we will insert the following document into the collection of counters with the key productid −

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

The sequence_value field keeps track of the last value of the sequence.

Use the following code to insert this sequence document into the counters collection −

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

Creating a Javascript function

We will now create a getNextSequenceValue function that will take the sequence name as input, increment the sequence number by 1, and return the updated sequence number. In our case, 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 ; }

Using a Javascript Function

We will now use the getNextSequenceValue function when creating a new document and assigning the returned sequence value as the document's _id field.

Insert two sample document using the following code −

> 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 used the getNextSequenceValue function to set the value for the _id field.

To test the functionality, let's download the documents using the find command −

>db.products.find()

The above query returned the following documents with auto-increment _id field −