How to create auto increment id in MongoDB

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.

  1. Generate a collection
  2. Insert a document into a collection
  3. Insert the record into a collection
  4. Database sequence
  5. Create a JavaScript function
  6. Use JavaScript function
  7. 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.

MongoDB auto increment id

Thus, By following all the steps to auto increment id in MongoDB successfully.

You may also like to read the following MongoDB tutorials.

In this tutorial, we learned about “MongoDB Auto Increment ID” and covered it with an example.

Top 200 SQL Server Interview Questions and Answers

Free PDF On Top 200 SQL Server Interview Questions And Answers

Download A 40 pages PDF And Learn Now.