In this MongoDB tutorial, we are going to learn how to generate the MongoDB Auto Increment ID.
We want the _id field 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"
}
MongoDB doesn’t support auto-increment features, unlike a relational database. We can perform this functionality by creating a collection and the collection will have a document that tracks the unique identifier.
Let’s follow the below steps to generate the MongoDB auto-increment id:
- 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 store collection
1. Generate a collection:
We create a collection with any name (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 having item_id its key.
{
"_id" : "item_id",
"sequence_value": 0
}
Here, The sequence_value field is used to keeps 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:
Now 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 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 having the auto-increment id field.

Thus, By following all the steps, we successfully create a MongoDB auto-increment id.
You may also like to read the following MongoDB tutorials.
- MongoDB two-phase commit
- MongoDB find string contains
- MongoDB find by ID
- MongoDB text search partial words
- 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
So in this tutorial, we have learned about “MongoDB Auto Increment ID” and covered it with the help of 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.