MongoDB Auto-Increment Sequence - MongoDB

How Auto increment sequence works?

There is no out-of-the-box auto-increment functionality, like SQL databases in MongoDB. By default, it will use 12-byte ObjectId for the _id field as the primary key for uniquely identifying the documents. However, there can be scenarios where we may want the _id field to have some auto-incremented value rather than the ObjectId.

As this is not a default feature in MongoDB, this functionality can be achieved programmatically by using a counters collection as suggested in MongoDB documentation.

Using Counter Collection

Consider below products document. We want the _id field to be an auto-incremented integer sequence starting from 1,2,3,4 upto n.

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

Now, insert below document in the counters collection with productid as its key

Field sequence_value will keep track of the last value of the sequence.

Use below code to insert this sequence document in the counters collection

Creating Javascript Function

Now, create a function getNextSequenceValue which takes the sequence name as its input, increments the sequence number by 1 and returns the updated sequence number. In this case, sequence name is productid.

Using the Javascript Function

Let’s use the function getNextSequenceValue while creating a new document and assign the returned sequence value as document's _id field.

Insert two sample documents using below code

Observe that we have used getNextSequenceValue function to set value for the _id field.

To check the functionality, fetch the documents using find command

Above query has returned below documents having the auto-incremented _id field

All rights reserved © 2018 Wisdom IT Services India Pvt. Ltd DMCA.com Protection Status

MongoDB Topics