Generate MongoDB Auto Increment Sequence – In 7 Easy Steps
Let's explore how to implement Auto Increment Sequence in MongoDB. We'll also look at how to set it up in 7 simple steps using a practical example.
What is MongoDB Auto Increment Sequence?
Why Use It?
MongoDB does not have built-in support for auto-increment like SQL databases. Instead, it uses a 12-byte ObjectId as the default primary key. But in many real-life situations (like ordering systems or invoice numbers), we need a simple number sequence like 1, 2, 3…
We can simulate this auto-increment behavior using a counter collection and a JavaScript function.
Steps to Create Auto Increment Sequence in MongoDB
1. Create a Sample Collection
First, create a collection that will act like a counter (similar to a sequence in traditional databases):
> db.createCollection("sample") { "ok" : 1 }
2. Insert Initial Sequence Document
Now insert an initial document into this sample collection:
> db.sample.insert({ _id: "item_id", sequence_value: 0 })
This document will keep track of the current counter value.
3. Create JavaScript Function
This function will fetch the current value and increase it by 1 each time it's called:
function getValueForNextSequence(sequenceName){ var sequenceDoc = db.sample.findAndModify({ query: { _id: sequenceName }, update: { $inc: { sequence_value: 1 } }, new: true }); return sequenceDoc.sequence_value; }
4. Insert Records Using Auto-Increment ID
Now use the function to insert documents in another collection (STORE) with auto-incremented _id values:
> db.STORE.insert({ _id: getValueForNextSequence("item_id"), item_short_name: "ABC", specification: "book", category: "fictional", seller: "best_buy", network: "XYZ", plan: "regular" })
You can insert more entries the same way:
> db.STORE.insert({ _id: getValueForNextSequence("item_id"), item_short_name: "DEF", specification: "book", category: "fictional", seller: "best_buy", network: "GHI", plan: "premium" })
5. View Inserted Records
Check your inserted documents using:
> db.STORE.find().pretty()
Sample Output:
{ "_id": 1, "item_short_name": "ABC", "specification": "book", "category": "fictional", "seller": "best_buy", "network": "XYZ", "plan": "regular" } { "_id": 2, "item_short_name": "DEF", ... }
Summary
That’s it! You’ve learned how to simulate an auto increment sequence in MongoDB using a simple counter collection and a JavaScript function in 7 easy steps. This method is handy for applications that need numeric IDs.
If you have any questions, feel free to drop a comment or join our MongoDB training sessions at DebugShala!
Write A Comment
No Comments