Web Programming TutorialsLearn How To Auto-Increment Sequences in MongoDB

Learn How To Auto-Increment Sequences in MongoDB

In relational databases like Oracle, IBM DB2, Sybase, etc., you might have heard about the term database sequence. The database sequence is a database product that creates unique values by getting an auto increment with a value which could be of a step of 1, 2, and so on. This sequence is very important as if a transaction id is associated with a sequence then the associated incremented number with the sequence will always be unique and never overlap. Not only this when we have multithreaded application then use of database sequence is the best approach for the serialization as two transactions cannot pick the same number.

It may sound quite surprising, but it is true that MongoDB has no such auto-increment functionality as we just discussed for the various relational databases. We may be familiar with the MongoDB’s 12-byte ObjectId which is used as the _id field and serves as the primary key to identify a document within a collection uniquely. But this is not sufficient as when we develop any software application, then we may get into a situation where we may need to use the _id field in order to procure the auto-incremented values other than the ObjectId. Though MongoDB do not support database sequence as a default feature, this functionality could still be achieved programmatically with the help of using counter collection. This approach to get a database sequence in MongoDB is suggested in the MongoDB documentation.

Using Counter Collection to generate a sequence
Below is a situation where we may need the _id field to be an auto-incremented integer sequence that starts from 1, 2, 3, and so on as the item id of an item store.

{
  "_id":1,
  "item_short_name": "Samsung S7",
  "specification": "4G Phone",
  "category": "cell_phones",
  "seller": "best_buy",
  "network": "Rogers",
  "plan": "regular"
}

We need to obey the following steps in MongoDB in order to generate the sequence for the item id.

Step 1: – Firstly, create a counter 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 traditional relational database sequence.

Microsoft Windows [Version 10.0.14393]
(c) 2016 Microsoft Corporation. All rights reserved.

C:\Users\Aparajita>cd C:\Program Files\MongoDB\Server\3.2\bin

C:\Program Files\MongoDB\Server\3.2\bin>mongo.exe
MongoDB shell version: 3.2.10
connecting to: test
> db.createCollection("counter")
{ "ok" : 1 }
>

Step 2: – Next, we will be inserting the following document in the counter collection which has the item_id as its key as shown below.

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

Step 3: – Use the following syntax to insert the above record into the counter collection.

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

Step 4: – Now use this counter collection like a database sequence in order to auto generate the item_id as shown below.

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

Step 5: – Create a JavaScript function to increment the value of the sequence_value field of the counter collection, as shown below.

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

Step 6: – Next, 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.ITEMS_STORE.insert({
...   "_id": getValueForNextSequence("item_id"),
...   "item_short_name": "Samsung S7",
...   "specification": "4G Phone",
...   "category": "cell_phones",
...   "seller": "best_buy",
...   "network": "Rogers",
...   "plan": "regular"
... })
WriteResult({ "nInserted" : 1 })
> db.ITEMS_STORE.insert({
...   "_id": getValueForNextSequence("item_id"),
...   "item_short_name": "Apple iPhone7",
...   "specification": "4G Phone Jet Black",
...   "category": "cell_phones",
...   "seller": "best_buy",
...   "network": "Telus",
...   "plan": "premium"
... })
WriteResult({ "nInserted" : 1 })
> db.ITEMS_STORE.insert({
...   "_id": getValueForNextSequence("item_id"),
...   "item_short_name": "Google Nexus 7",
...   "specification": "4G Phone Red color",
...   "category": "cell_phones",
...   "seller": "best_buy",
...   "network": "Bell",
...   "plan": "corporate"
... })
WriteResult({ "nInserted" : 1 })
>

Step 7: – Next, we can view the inserted records from the ITEMS_STORE collection by using the find and pretty methods of the MongoDB as shown below.

> db.ITEMS_STORE.find().pretty()
{
        "_id" : 1,
        "item_short_name" : "Samsung S7",
        "specification" : "4G Phone",
        "category" : "cell_phones",
        "seller" : "best_buy",
        "network" : "Rogers",
        "plan" : "regular"
}
{
        "_id" : 2,
        "item_short_name" : "Apple iPhone7",
        "specification" : "4G Phone Jet Black",
        "category" : "cell_phones",
        "seller" : "best_buy",
        "network" : "Telus",
        "plan" : "premium"
}
{
        "_id" : 3,
        "item_short_name" : "Google Nexus 7",
        "specification" : "4G Phone Red color",
        "category" : "cell_phones",
        "seller" : "best_buy",
        "network" : "Bell",
        "plan" : "corporate"
}
>

Here, we can clearly observe that the item_id for these inserted records are 1, 2 and 3 as an auto incremented sequence of step 1 which is very similar to that of the traditional relational database sequence.

Conclusion: –
In this article, we discussed about the use of the auto increment sequence in the MongoDB along with a suitable example. Although, there is no direct database sequence command present in the MongoDB as compared to the various relational databases but auto increment sequences of variable step sizes can be formulated with the help of the counter collection and the JavaScript function where we increment the sequence value specified in the counter collection. This JavaScript function can be used to fetch the sequence value in order to use and insert the sequence value as the field value of a particular document in MongoDB’s insertion scripts.

1 COMMENT

  1. Nice article.
    Please could you suggest how to use this with mongoose schema?
    My requirement is to create 2 counters, 1 for parent and another for child schema.

    Thanks

LEAVE A REPLY

Please enter your comment!
Please enter your name here

Exclusive content

- Advertisement -

Latest article

21,501FansLike
4,106FollowersFollow
106,000SubscribersSubscribe

More article

- Advertisement -