MongoDB does now not have out-of-the-container vehicle-increment functionality, like SQL databases. By default, it uses the 12-byte ObjectId for the _id discipline because the primary key to uniquely pick out the files. However, there may be scenarios where we may also need the _id subject to have a few automobile-incremented fee other than the ObjectId.
Since this isn't always a default feature in MongoDB, we can programmatically gain this capability by the use of a counters series as counseled by the MongoDB documentation.
Using Counter Collection
Consider the following products file. We need the _id discipline to be an car-incremented integer collection starting from 1,2,3,four upto n.
{
"_id":1,
"product_name": "Apple iPhone",
"category": "mobiles"
}
For this, create a counters series, which will preserve song of the last series fee for all of the sequence fields.
>db.createCollection("counters")
Now, we can insert the subsequent report within the counters series with productid as its key −
> db.counters.insert({
"_id":"productid",
"sequence_value": 0
})
WriteResult({ "nInserted" : 1 })
>
The discipline sequence_value keeps track of the closing value of the sequence.
Use the following code to insert this series file within the counters collection −
>db.counters.insert({_id:"productid",sequence_value:0})
Creating Javascript Function
Now, we will create a characteristic getNextSequenceValue so as to take the collection name as its enter, increment the sequence number by 1 and return the updated series wide variety. In our case, the series 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
We will now use the feature getNextSequenceValue whilst growing a brand new record and assigning the lower back sequence value as report's _id field.
Insert pattern files the usage of 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 may see, we've used the getNextSequenceValue feature to set cost for the _id subject.
To affirm the functionality, let us fetch the files the use of discover command −
>db.products.find()
The above question lower back the subsequent files having the car-incremented _id subject −
{ "_id" : 1, "product_name" : "Apple iPhone", "category" : "mobiles"}
{ "_id" : 2, "product_name" : "Samsung S3", "category" : "mobiles" }