Home >>MongoDB Tutorial >MongoDB Auto-Increment Sequence

MongoDB Auto-Increment Sequence

MongoDB Auto-Increment Sequence

Like SQL databases, MongoDB has no out-of-the-box auto-increment features. By default, the 12-byte ObjectId for the _id field is used as the primary key to mark the documents uniquely. There might be situations, however where we may want to provide some auto-incremented value other than ObjectId in the _id field.

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

Using Counter Collection

Consider the following document about products. Starting from 1,2,3,4 up to n, we want the id field to be an auto-incremented integer sequence.

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

Build a collection of counters for this which keeps track of the last sequence value for all sequence fields.

>db.createCollection("counters")

We will now insert the following document into the collection of counters with productid as its key-

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

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

To insert this sequence document in the counter set, use the following code –

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

Creating Javascript Function

Now we're going to create a getNextSequenceValue function that will take the sequence name as its input, increase the sequence number by 1, and return the sequence number that has been updated. The name of the sequence in our case 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 the Javascript Function

When creating a new document, we can now use the getNextSequenceValue function and assign the returned sequence value to the document as the _id field.

Using the following code to insert two sample documents −

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

Let us fetch the documents using the find command to check the features.

>db.products.find()

The above query returned the following documents with the field of auto-incremented_id –

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

No Sidebar ads