MongoDB Auto Increment ID

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:

  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 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.

MongoDB auto increment id
MongoDB Auto Increment ID

Thus, By following all the steps, we successfully create a MongoDB auto-increment id.

You may also like to read the following MongoDB tutorials.

So in this tutorial, we have learned about “MongoDB Auto Increment ID” and covered it with the help of an example.