MongoDB Auto-Increment
MongoDB does not have an auto-increment feature like SQL does, MongoDB's _id is a system-generated 12-byte unique identifier.
However, in some cases, we might need to implement an auto-increment functionality for ObjectId.
Since MongoDB does not implement this feature, we can achieve it through programming. Below, we will implement auto-increment for 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 achieve this, create a counters collection where the sequence field value can be auto-incremented:
>db.createCollection("counters")
Now, 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 of the sequence after auto-increment.
Insert the sequence document into the counters collection using the following command:
>db.counters.insert({_id: "productid", sequence_value: 0})
Creating a Javascript Function
Now, create the function getNextSequenceValue to take a sequence name as input, which will auto-increment the specified sequence 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;
}
Using the Javascript Function
Next, we will use the getNextSequenceValue function to create a new document and set the document _id 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 the function's effectiveness, we can read the documents using the following command:
>db.products.find()
The above command will return the following result, showing that the _id field is auto-incremented:
{ "_id" : 1, "product_name" : "Apple iPhone", "category" : "mobiles"}
{ "_id" : 2, "product_name" : "Samsung S3", "category" : "mobiles" }