Auto Increment in MongoDB

Auto increment or sequence generator is a process or functionality that returns a unique value. In SQL Server has a functionality where we can generate auto incremented numbers for any key. But mostly we used this auto incremented for primary key of a table. Unlike SQL Server, MongoDB doesn't have this cool feature. MongoDB generates _id field if not provided. It is a ObjectId generated by using timestamp, machine ID and process ID and process local incremental counter as stated on MongoDB manual. But some times we need a user friendly auto incremented unique value to represent as primary/any key on a collection. It is not a native feature in MongoDB but can be achieved programmatically.


Using counter Collection:

We can have a separate counter collection to keep track of the sequence. We can use _id or any field for the sequence name. If we want to generate sequence no for each collection, can be keep the collection names as sequence names.

db.sequenceCounters.insert([
  {
    _id: "users",
    nextSequence: 1
  },
  {
    _id: "products",
    nextSequence: 1
  }
]);

Create a method to generate a sequence number, so we can have it (auto incremented sequence number) before needs. In this method we can use findAndModify method to do the same. It modify and return the single document.

function getNextSequence(sequenceName, counter) {
   var ret = db.sequenceCounters.findAndModify(
          {
            query: { _id: sequenceName },
            update: { $inc: { nextSequence: counter}},
            new: true
          }
   );

   return ret.seq;
}

By default the counter value is 1. Some times we may need to insert multiple records so we can achieve this by supplying no of records need to insert. So we can achieve this on a single database connection.

The next step is to use the use the above getNextSequence method to generate the sequence number and use it on the specific collection.

db.users.insert(
   {
     _id: getNextSequence("users", 1),
     name: "Srikant Biswal"
   }
);

db.products.insert(
   {
     _id: getNextSequence("products", 1),
     name: "Samsung Note 8"
   }
);

db.products.insert(
   {
     _id: getNextSequence("products", 1),
     name: "Ipad Mini"
   }
);

Lets verify the records on database.

db.users.find();
db.products.find();

{
  "_id" : 1,
  "name" : "Srikant Biswal"
}

{
  "_id" : 1,
  "name" : "Samsung Note 8"
}

{
  "_id" : 2,
  "name" : "Ipad Mini"
}

Conclusion:

In this tutorial, I have explained the auto increment/sequence generator on MongoDB. I will add more in my next article.


Reference:

http://docs.mongodb.org/


Discussion
5 X 6 =
** To prevent abusing comments from publishing, posted comments will be reviewed and then published!
 Srikant Biswal

More from me...
MongoDB Restore
about 3 years ago 1526 Views
MongoDB Backup
about 3 years ago 1434 Views
MongoDB Data Model
about 3 years ago 1215 Views
MongoDB Read
about 3 years ago 1460 Views
Mongo DB crud operation
about 3 years ago 1736 Views