MongoDB Auto-Increment
MongoDB does not have an auto-increment feature like SQL; MongoDB's _id is a 12-byte unique identifier automatically generated by the system.
But in some cases, we may need to implement an ObjectId auto-increment feature.
Since MongoDB does not implement this feature, we can implement it programmatically. Below we will implement auto-increment of the _id field in the counters collection.
Using the counters collection
Consider the following products document. We want the _id field to auto-increment from 1, 2, 3, 4 to n.
{
"_id":1,
"product_name": "Apple iPhone",
"category": "mobiles"
}
To do this, create the counters collection, where 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 a value after the sequence has auto-incremented.
Use the following command to insert into the sequence document of the counters collection:
>db.counters.insert({_id:"productid",sequence_value:0})
Creating a Javascript function
Now we create the function getNextSequenceValue to take the sequence name as input. The specified sequence will auto-increment by 1 and return the latest sequence value. In the example in this article, 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 the Javascript function
Next we will use the getNextSequenceValue function to create a new document, and set the document _id automatically to the returned sequence value:
>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 that the function works, we can use the following command to read the document:
>db.products.find()
The above command will return the following result, and we find that the _id field is auto-incrementing:
{ "_id" : 1, "product_name" : "Apple iPhone", "category" : "mobiles"}
{ "_id" : 2, "product_name" : "Samsung S3", "category" : "mobiles" }