MongoDB Create an Auto-Increment Sequence Field

By Yashwant Chavan, Views 40985, Last updated on 13-Oct-2016

In this tutorial we will learn how to create an auto increment sequence field using mongoDB. MongoDB creates a unique index on the _id field while creating collection. By default mongoDB uses standard auto generated ObjectId to maintain the sequence / uniqueness for _id field in the document.

tags mongodb

ObjectId is a hexadecimal string value for the new ObjectId which helps to prevents clients from inserting two documents with the same field values with unique _id field.

Mongodb Counter Collection

In below example we will create auto incrementing sequence to maintain the unique roll number for student documents. Lets create the studentcounters collection, which contains the _id and seq field to maintain the auto-incremented sequence numbers starting from 1,2,3....

> use technicalkeeda
switched to db technicalkeeda
> db.studentcounters.insert(
{
 _id: "rollNo",
 seq: 0
}
)
WriteResult({ "nInserted" : 1 })
>

Create Sequence Function

Create a getStudentSequence() function with single input parameter of sequence name. The function uses the findAndModify() method to atomically increment the seq value on each execution of this getStudentSequence() function.

> function getStudentSequence(sequenceName) {
 var result = db.studentcounters.findAndModify(
  {
   query: { _id: sequenceName },
   update: { $inc: { seq: 1 } },
   new: true
  }
 );
 return result.seq;
}
>

Use Sequence function while inserting documents

Use getStudentSequence() function while inserting new documents into collection and assign its return value to document's _id field. So that while each insertion of document it will increment the _id field value.

> db.students.insert(
{
      _id: getStudentSequence("rollNo"),
      name: "Yashwant Chavan",
  class : "XI"
 }
 )
WriteResult({ "nInserted" : 1 })

> db.students.insert(
 {
      _id: getStudentSequence("rollNo"),
      name: "Mahesh Patil",
  class : "XI"
 }
 )
WriteResult({ "nInserted" : 1 })

> db.students.insert(
 {
      _id: getStudentSequence("rollNo"),
      name: "Dinesh More",
  class : "XI"
 }
 )
WriteResult({ "nInserted" : 1 })

>

Display Collection

To verify the changes, print students collection data using db.students.find() command, It will return the list of documents having the auto-incremented _id field values

> db.students.find().pretty()

{ "_id" : 1, "name" : "Yashwant Chavan", "class" : "XI" }
{ "_id" : 2, "name" : "Mahesh Patil", "class" : "XI" }
{ "_id" : 3, "name" : "Dinesh More", "class" : "XI" }

>
Yashwant

Yashwant

Hi there! I am founder of technicalkeeda.com and programming enthusiast. My skills includes Java,J2EE, Spring Framework, Nodejs, PHP and lot more. If you have any idea that you would want me to develop? Lets connect: yashwantchavan[at][gmail.com]