Mongodb Autoincrement Sequence
# MongoDB Auto-Increment
MongoDB does not have an auto-increment feature like SQL. MongoDB's _id is a system-generated 12-byte unique identifier.
However, in some cases, we may need to implement an auto-incrementing ObjectId feature.
Since MongoDB does not implement this feature, we can achieve it through programming. Below, we will implement auto-increment for the _id field in a 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 auto-increment:
>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 after the sequence has auto-incremented.
Use the following command to insert the sequence document into the counters collection:
>db.counters.insert({_id:"productid",sequence_value:0})
* * *
## Creating a Javascript Function
Now, we create a function getNextSequenceValue that takes a sequence name as input. The specified sequence will auto-increment 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's _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 if the function works, we can use the following command to read the documents:
>db.products.find()
The above command will return the following results, showing that the _id field is auto-incrementing:
{ "_id" : 1, "product_name" : "Apple iPhone", "category" : "mobiles"}{ "_id" : 2, "product_name" : "Samsung S3", "category" : "mobiles" }
YouTip