Understanding the mongoose _id field

Have a Database Problem? Speak with an Expert for Free
Get Started >>

Introduction

MongoDB is one of the most popular NoSQL databases. It stores data in the BSON format. BSON format is an extension of the JSON format that provides more data types. Have a look at the following document.

1
2
3
4
5
6
7
8
9
{

    "name" : "Rambo",
    "age": 5,
    "isAdopted" : false,
    "foodPref" : ["Meat", "Milk"]


}

The above document contains the detail of a dog and has four fields. Each of them contains the value of a different data type. Similarly, there can be several other documents describing other dogs. Imagine having five hundred different documents. Various documents can have the same value for the name field, or age field, or any other field. We need a primary key that a unique value for each document. It is a good practice to have a primary key in a database. We do not need to create it ourselves because MongoDB itself provides a primary key for each document. This primary key provided by MongoDB is the _id field that is automatically created when a document is inserted into a collection. In this article, we will discuss about the _id field.

For performing HTTP endpoint testing, we will use the postman tool. You can download the postman tool from www.getpostman.com.

_id field

We can insert documents in a collection through a mongo shell. Another way of inserting documents is through mongoose or simply said, through post request. There are various methods for inserting documents. As mentioned earlier, the _id field is automatically generated when a document is inserted into a collection. So let’s add a document through mongoose.

The following route handler will be invoked when the endpoint ‘/insert’ is executed.

1
2
3
4
5
6
7
8
9
router.route("/insert").post(function(req, res) {
  kennel.create({ name: "rambo" }, function(err, result) {
    if (err) {
      res.send(err);
    } else {
      res.send(result);
    }
  });
});

This route handler creates a post request and inserts a single document in the kennel collection. Currently, we inserting a document with one key-value pair.

1
{"name" : "rambo"}

Let’s execute this route using the postman tool.

Image from Gyazo

The create() method returns the document that was inserted into the collection. It contains three key-value pairs. But the document, we specified only had one key-value pair. So what are these two extra key-value pairs? One is __v field and the other is the _id field. When a document is inserted through mongoose, these two are automatically generated but when inserted through mongo shell, only _id field is generated.

Let’s discuss the _id field. We can see it is a string that contains alphabets and digits. This value will be unique throughout the collection. No other document will have the same value for the _id field. Let’s add three more documents in this collection. We will use the insertMany() method.

1
2
3
4
5
6
7
8
9
10
11
12
router.route("/insert").post(function(req, res) {
  kennel.insertMany(
    [{ name: "scooby" }, { name: "romeo" }, { name: "spike" }],
    function(err, result) {
      if (err) {
        res.send(err);
      } else {
        res.send(result);
      }
    }
  );
});

Image from Gyazo

The following are the values of the _id field in all the documents.

1
2
3
4
"5ddf76af01c5992ec4fa1c9c";
"5ddf784f9dbb9f1530b96020";
"5ddf784f9dbb9f1530b96021";
"5ddf784f9dbb9f1530b96022";

Observe these values. Each of them is unique. This is how the _id field acts as the primary key.

Conclusion

Thank you for joining us for this article on explaining the _id field. To recap the _id field is automatically created by MongoDB to uniquely identify objects, and it is not an added functionality of Mongoose. While Mongoose does add some data to the documents like the __v field which we discussed, the _id field is native to MongoDB.

We hope you enjoyed our discussion of the _id field and that the information in this article helped you understanding the _id field. If you have any database needs please don’t hesitate to reach out to us at Object Rocket.

Just The Code

1
2
3
4
5
6
7
8
9
router.route("/insert").post(function(req, res) {
  kennel.create({ name: "rambo" }, function(err, result) {
    if (err) {
      res.send(err);
    } else {
      res.send(result);
    }
  });
});
1
2
3
4
5
6
7
8
9
10
11
12
router.route("/insert").post(function(req, res) {
  kennel.insertMany(
    [{ name: "scooby" }, { name: "romeo" }, { name: "spike" }],
    function(err, result) {
      if (err) {
        res.send(err);
      } else {
        res.send(result);
      }
    }
  );
});

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.