Generate MongoDB Auto Increment Sequence – In 7 Steps

In the last tutorial, we had learned about MongoDB Covered & Analyzing Query. Now we will discuss what is MongoDB Auto Increment sequence. Along with this, we will learn steps to generate auto increment sequence with an example.

MongoDB Auto Increment Sequence

How to MongoDB Auto Increment Sequence?

1. How MongoDB Auto Increment Sequence Works?

MongoDB does not support auto-increment functionality as it is available in SQL databases. We all may be familiar with MongoDB’s 12-byte ObjectId which is used as a primary key to identify documents within a collection uniquely. But this is not fit for real-time operations in our day to day life. Although MongoDB does not support autoincrement sequence as a default feature, this functionality can be achieved programmatically with the help of using a counter collection.

Using Counter Collection to generate a sequence-

In the below condition, we require the _id field for auto incremented integer sequence. This will start with 1,2,3,4,5 and so on.

{
   "_id":1,
   "item_short_name": "ABC",
   "specification": "Book",
   "category": "fictional",
   "seller": "best_buy",
   "network": "XYZ",
   "plan": "regular"
}

Do you know What is MongoDB Covered & Analyzing Query?

2. How to Generate Auto Increment Sequence in MongoDB?

Let’s use the following steps to generate the MongoDB auto increment sequence for the item id:

  1. Generate sample collection
  2. Insert a document into a collection
  3. Insert the record into a collection
  4. Database sequence
  5. Create a JavaScript function
  6. Use JavaScript function
  7. View inserted a record from store collection

i. Generate sample collection

To generate a sample collection using the following syntax. This counter will keep track of the last sequence value for all the sequence fields, as it is done in the case of a traditional database sequence.

> db.createCollection("sample")
{ "ok" : 1 }
>

ii. Insert a document in a collection

Insert the below document in sample collection which is having item_id as its key.

{
   "_id" : "item_id",
   "sequence_value": 0
}

iii. Insert the record into a collection

Use the given below syntax to insert the above record into sample collection.

> db.sample.insert ( {_id: "item_id" , sequence_value : 0 } )
WriteResult ( { "nInserted" : 1 } )
>

iv. Database Sequence

Now use this sample collection as a database sequence in order to auto generate the item_id as shown below:

> db.sample.insert ( {_id: "item_id" , sequence_value : 0 } )
WriteResult ( { "nInserted" : 1 } )
>

Recommended Reading – MongoDB Data Modeling & Document Structure

v. Create a JavaScript Function

Here, create a JavaScript function to increment the value of the sequence_value field of the sample collection, as shown below:

> function getValueForNextSequence(sequenceOfName){
...
...   var sequenceDoc = db.sample.findAndModify({
...     query:{_id: sequenceOfName },
...      update: {$inc:{sequence_value:1}},
...      new:true
...    });
...
...     return sequenceDoc.sequence_value;
... }
>

vi. Use JavaScript Function

Now we are going to use this JavaScript function in order to generate an auto increment sequence value of step 1 as the item_id. The following are the database scripts.

> db.STORE.insert({
... "_id": getValueForNextSequence("item_id"),
... "item_short_name": "ABC",
... "specification": "book",
... "category": "fictional",
... "seller": "best_buy",
... "network": "XYZ",
... "plan": "regular"
... })
WriteResult({ "nInserted" : 1 })
> db.STORE.insert({
... "_id": getValueForNextSequence("item_id"),
... "item_short_name": "DEF",
... "specification": "book",
... "category": "fictional",
... "seller": "best_buy",
... "network": "GHI",
... "plan": "premium"
... })
WriteResult({ "nInserted" : 1 })
> db.STORE.insert({
... "_id": getValueForNextSequence("item_id"),
... "item_short_name": "JKL",
... "specification": "books",
... "category": "non-fictional",
... "seller": "best_buy",
... "network": "MNO",
... "plan": "corporate"
... })
WriteResult({ "nInserted" : 1 })
>

Also, See – MongoDB Limit and Skip() Method

vii. View inserted record from store collection

Now we can view the inserted records from the STORE collection by using the find and pretty methods.

> db.STORE.find().pretty()
{
    "_id" : 1,
    "item_short_name" : "ABC",
    "specification" : "fictional",
    "category" : "books",
    "seller" : "best_buy",
    "network" : "XYZ",
    "plan" : "regular"
}
{
    "_id" : 2,
    "item_short_name" : "DEF",
    "specification" : "fictional",
    "category" : "books",
    "seller" : "best_buy",
    "network" : "GHI",
    "plan" : "premium"
}
{
    "_id" : 3,
    "item_short_name" : "JKL",
    "specification" : "non-fictional",
    "category" : "books",
    "seller" : "best_buy",
    "network" : "MNO",
    "plan" : "corporate"
}
>

So, by using the following steps, we can create a MongoDB auto increment sequence.

3. Summary

Hence, we have studied the 7 steps to generate MongoDB auto increment sequence with JavaScript function and example. Furthermore, if you have any query, feel free to ask in the comment section.

Related Topic – MongoDB Text Search

Leave a Reply

Your email address will not be published. Required fields are marked *

This site is protected by reCAPTCHA and the Google Privacy Policy and Terms of Service apply.