Auto Increment Sequence in MongoDB

Introduction

If you’re accustomed to working with SQL databases, you’ve probably had some experience with auto-increment sequences. This functionality automatically generates a unique value when a new row is added to a table. Although auto-increment functionality isn’t built into MongoDB, it’s possible to achieve the same results with a simple alternative. In this article, we’ll walk you through the steps needed to create an auto increment sequence in MongoDB.

Prerequisite

Before proceeding with this tutorial, be sure that MongoDB is already installed and configured on your system.

MongoDB Auto Increment Sequence Overview

Unlike SQL databases, the auto-increment feature is not supported in MongoDB. MongoDB does provide the ObjectId, which can be used as a primary key– a value that makes each document unique within a collection. This functionality is useful to a certain degree, but not sufficient for real-time operations.

Although MongoDB doesn’t support the auto-increment sequence feature by default, it’s easy to achieve the same functionality using a counter collection.

Let’s take a look at the following example, which shows that the value of _id will be the result of an auto-incremented sequence:

1
2
3
4
5
6
7
{
"_id":1,
"student_id": "02940409",
"course": "Bachelor of Science in Computer Engineering",
"year_level": "2nd",
"department": "engineering"
}

In the document shown above, we can see that the value of ObjectId will be an auto incremented sequence starting with the value of ‘1’.

Generating MongoDB Auto Increment Sequence

Now that we’ve reviewed the basics of how auto-increment works with MongoDB, let’s look at how to generate our own auto increment sequence in MongoDB.

Create a Sample Collection

In this section, we’ll be creating a sample collection named student within the database named schooldb.

To do this, we’ll use the following syntax in the Mongo shell:

1
2
3
4
> use schooldb
switched to db schooldb
> db.createCollection("student")
{ "ok" : 1 }

In the code shown above, we used the Mongo shell command use, specifying the name of our database. After creating the database, we created our collection using the db.createCollection() method.

Insert Document

Now that we’ve created our database and collection, let’s look at how to insert a document into that collection:

db.student.insert ( {_id: “itemId” , seqValue : 0 } );

Create A Function

Our next step will be to create a function that will increment the value of the variable seqValue within the student collection. The code for this function is shown below:

1
2
3
4
5
6
7
8
9
function getSequenceNextValue(seqName) {
  var seqDoc = db.student.findAndModify({
    query: { _id: seqName },
    update: { $inc: { seqValue: 1 } },
    new: true
  });

  return seqDoc.seqValue;
}

Using the JavaScript Function

In the previous section, we created a JavaScript function called getSequenceNextValue. Now we’ll show you how to use that function in the Mongo shell to increment the value of the seqValue variable by one.

Here’s how it works:

1
2
3
4
5
6
7
db.student.insert({
  _id: getSequenceNextValue("itemId"),
  student_id: "02940409",
  course: "Bachelor of Science in Computer Engineering",
  year_level: "2nd",
  department: "engineering"
});

After we execute this command, MongoDB will notify us with the following response: WriteResult({ "nInserted" : 1 })

Let’s try to insert some more documents into the student collection:

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
> db.student.insert({
... "_id": getSequenceNextValue("itemId"),
... "student_id": "02740305",
... "course": "Bachelor of Science in Finance",
... "year_level": "2nd",
... "department": "Business Administration"
... });
WriteResult({ "nInserted" : 1 })
> db.student.insert({
... "_id": getSequenceNextValue("itemId"),
... "student_id": "02550409",
... "course": "Bachelor of Science in Architecture",
... "year_level": "2nd",
... "department": "engineering"
... });
WriteResult({ "nInserted" : 1 })

Verify The Inserted Record

In the previous section, we inserted documents into the student collection. Now, let’s verify whether we successfully auto-incremented our _id.

We’ll use the following command: db.student.find().pretty();

The output should look something like this:

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
{ "_id" : "itemId", "seqValue" : 3 }
{
"_id" : 1,
"student_id" : "02940409",
"course" : "Bachelor of Science in Computer Engineering",
"year_level" : "2nd",
"department" : "engineering"
}
{
"_id" : 2,
"student_id" : "02740305",
"course" : "Bachelor of Science in Finance",
"year_level" : "2nd",
"department" : "Business Administration"
}
{
"_id" : 3,
"student_id" : "02550409",
"course" : "Bachelor of Science in Architecture",
"year_level" : "2nd",
"department" : "engineering"
}

Conclusion

If you’re looking to auto-increment values for a specific field, you’ll find that this functionality isn’t built into MongoDB. However, it’s still easy to achieve the same results by using a counter collection. In this article, we provided step-by-step instructions for creating an auto increment sequence in MongoDB. With our examples to guide you, you’ll be able to implement the same functionality in your own MongoDB collections.

Pilot the ObjectRocket Platform Free!

Try Fully-Managed CockroachDB, Elasticsearch, MongoDB, PostgreSQL (Beta) or Redis.

Get Started

Keep in the know!

Subscribe to our emails and we’ll let you know what’s going on at ObjectRocket. We hate spam and make it easy to unsubscribe.