How to Implement Auto Increment in MongoDB

MD Aminul Islam Feb 02, 2024
How to Implement Auto Increment in MongoDB

Most SQL query language contains a single keyword for making a field auto-increment, but it’s a bit complex in MongoDB. In MongoDB, there is no keyword available for auto-increment.

This article will show us how we can insert data in a MongoDB collection with the auto-increment functionality, and we will see an example relevant to the topic to make it easier.

Apply the Auto Increment Functionality in MongoDB

Some fields we need to increment after a new document is inserted in a collection include the serial number, ID, etc. But we can do this automatically if we add some simple characters to our query.

The keyword we will use for this purpose is $inc, incrementing the specific data value. Let’s see how we can integrate it into our query.

In our below example, we will demonstrate how we use auto increment in MongoDB. For this purpose, first, we need to create a new collection named count that will track the sequence number.

Let’s initialize the collection by inserting a document like the one below.

db.count.insert(
   {
      _id: "incId",
      seq: 0
   }
)

This will initialize the incrementing sequence to 0. Now, we will create a function named autoIncrement() that will increment the value on both the count collection and the specified collection.

function autoIncrement(name) {
   var ret = db.count.findAndModify(
          {
            query: { _id: name },
            update: { $inc: { seq: 1 } },
            new: true
          }
   );

   return ret.seq;
}

The function will return the incremented sequence value, which we can use on our insert function by calling the function like the one below.

db.mycollection.insert({ sl: autoIncrement("incId"), Name: "Retro"});
db.mycollection.insert({ sl: autoIncrement("incId"), Name: "Max"});

After executing the above commands, you need not manually increment a field value. After inserting the document, you will get the below output in your console:

{ _id: ObjectId("6388f500054350812fa6b073"),
  sl: 1,
  Name: 'Retro' }
{ _id: ObjectId("6388f94e054350812fa6b075"),
  sl: 2,
  Name: 'Max'
}

Remember you can’t use one counting collection for incrementing values on multiple collections. The collection count is like a variable that holds and updates increment values, so you must create a counting collection for incrementing values on multiple collections.

Please note that the commands shown in this article are for the MongoDB database and the command needs to be run on the MongoDB console.

MD Aminul Islam avatar MD Aminul Islam avatar

Aminul Is an Expert Technical Writer and Full-Stack Developer. He has hands-on working experience on numerous Developer Platforms and SAAS startups. He is highly skilled in numerous Programming languages and Frameworks. He can write professional technical articles like Reviews, Programming, Documentation, SOP, User manual, Whitepaper, etc.

LinkedIn

Related Article - MongoDB Document