In this MongoDB tutorial, we will learn how to auto increment id in MongoDB.
How to create auto increment id in MongoDB
We want the _id field to be in an auto-increment sequence starting from 1, 2, 3, up to n. So consider the following documents.
{
"_id":1,
"item_name": "The Higgler",
"specification": "Book",
"series": "Romance"
}
Unlike a relational database, MongoDB doesn’t support auto-increment features. However, we can perform this functionality by creating a collection, which will have a document that tracks the unique identifier.
To create auto increment id in MongoDB, follow the below steps.
- Generate a 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 the store collection
1. Generate a collection:
We create a collection with any name (for example) by using the createCollection() method.
> db.createCollection("example")
{ "ok" : 1 }
2. Insert a document into a collection:
Insert a document into the student collection which is an item_id as its key.
{
"_id" : "item_id",
"sequence_value": 0
}
Here, the sequence_value field is used to keep track of the last value of the sequence.
3. Insert the record into a collection:
We will insert the above record into the example collection by using the insert() method.
> db.example.insert( {_id: "item_id" , sequence_value : 0 } )
WriteResult({ "nInserted" : 1 })
4. Database sequences:
Use this student collection as a database sequence to auto-generate the item_id:
> db.student.insert( {_id: "item_id" , sequence_value : 0 } )
Read MongoDB get collection size
5. Create a JavaScript Function:
Now, we will create a getNextSequence JavaScript function to increment the value of the sequence_value by 1 and also return the updated sequence number.
> function getNextSequence(sequenceName){
var sequenceDocument = db.example.findAndModify({
query:{_id: sequenceName },
update: {$inc:{sequence_value:1}},
new:true
});
return sequenceDocument.sequence_value;
}
6. Use JavaScript Function:
We will use the above JavaScript getNextSequence function to create an auto-increment sequence new document and assign the returned sequence value as the item_id field.
Here, we are inserting the following two documents into the example collection:
db.example.insert({
"_id": getNextSequence("item_id"),
"item_name": "The Grass is Always Greener",
"specification": "book",
"series": "Modern Times",
})
db.example.insert({
"_id": getNextSequence("item_id"),
"item_name": "Murder!",
"specification": "book",
"series": "Crime",
})
Here, we have used the getNextSequence function to set a value for the _id field.
7. View inserted a record from the stored collection:
We will check the documents of the example collection by using the find() method.
> db.example.find().pretty()
Now, the query will return the document with the auto-increment id field.

Thus, By following all the steps to auto increment id in MongoDB successfully.
You may also like to read the following MongoDB tutorials.
- MongoDB two-phase commit
- MongoDB find string contains
- MongoDB find by ID
- Create index in MongoDB
- MongoDB Update Documents
- Export MongoDB to CSV
- MongoDB remove a field from the document
- MongoDB join two collections
- Import CSV into MongoDB
- MongoDB drop collection
In this tutorial, we learned about “MongoDB Auto Increment ID” and covered it with an example.
I am Bijay having more than 15 years of experience in the Software Industry. During this time, I have worked on MariaDB and used it in a lot of projects. Most of our readers are from the United States, Canada, United Kingdom, Australia, New Zealand, etc.
Want to learn MariaDB? Check out all the articles and tutorials that I wrote on MariaDB. Also, I am a Microsoft MVP.