Generate MongoDB Auto Increment Sequence – In 7 Steps
Job-ready Online Courses: Knowledge Awaits – Click to Access!
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.
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" }
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:
- Generate sample collection
- Insert a document into a collection
- Insert the record into a collection
- Database sequence
- Create a JavaScript function
- Use JavaScript function
- 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 } ) >
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 }) >
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.
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.
Your opinion matters
Please write your valuable feedback about DataFlair on Google
Is this way safe in case there is a lot of insertion made at the same time? as I implemented a solution also but using count function, I was counting the documents and increment it but in some cases, I found a duplicate for the sequence
you recommend creating this javascript function getValueForNextSequence in mongo atlas? or can be stored as an object in the mongo database?