Mongoose Count

Introduction

There can be any number of documents in a collection. There is no limit for that. In our mongoose code, we may need to know how many documents are present in a particular collection. Or we may need to know how many documents are there with the same value for a particular field. Of course, there are methods that return all the documents in a collection or even return documents according to a particular condition. But to count the number of documents in a collection, mongoose has a method known as count. The count() method returns the number of documents in a collection. In this article, we will discuss the count method and two more methods – countDocuments() and estimatedDocumentCount().

count() method

We have the following documents in the collection.

{ "_id" : ObjectId("5d7bd742af53211676a05c66"), "name" : "John", "age" : 21, "location" : "New York" }
{ "_id" : ObjectId("5d7bd746af53211676a05c67"), "name" : "Sam", "age" : 23, "location" : "Texas" }
{ "_id" : ObjectId("5d7bd74baf53211676a05c68"), "name" : "Max", "age" : 26, "location" : "Chicago" }
{ "_id" : ObjectId("5d7bd771af53211676a05c69"), "name" : "Lisa", "age" : 25, "location" : "Texas" }
{ "_id" : ObjectId("5d7bd774af53211676a05c6a"), "name" : "Ronn", "age" : 28, "location" : "Texas" }

Let’s have a look at the route.

router.route("/countDocuments").get(function(req, res) {
  detail.count({}, function(err, result) {
    if (err) {
      console.log(err);
    } else {
      res.json("Number of documents in the collection: " + result);
    }
  });
});

Whenever the URL – ‘/countDocuments’, will be used, this function will be invoked. Inside the function, we used the count() method to count the number of documents in the detail collection. The count method has two arguments – an object and a callback function. The object can be empty or can contain a query.

In the function above, we are only passing an empty object. It will return the total number of documents in the collection. Let’s test this code using the postman tool.

Image from Gyazo

Yes! There are 5 documents in the collection. We can also provide a query in the empty object we passed as the first argument.

router.route("/countDocuments").get(function(req, res) {
  detail.count({ location: "Texas" }, function(err, result) {
    if (err) {
      console.log(err);
    } else {
      res.json("Number of documents in the collection: " + result);
    }
  });
});

Observe the first argument of the count method.

{"location" : "Texas"}

This will return the number of documents where the location is Texas. Let’s verify it.

Image from Gyazo

Yes! There are three documents in the collection where the location is Texas.

But the count() method is deprecated now. There are two new methods – countDocuments() and estimatedDocumentCount().

countDocuments() and estimatedDocumentCount()

The countDocuments() function is similar to the count method. It also returns the number of documents in a collection. The estimatedDocumentCount() method also returns the number of documents in a collection, but it should be used when there are a large number of documents.

The estimatedDocumentCount() method is fast. Rather than scanning the entire collection, it uses the metadata. One more difference between these two methods is that the estimatedDocumentCount() does not accept a filter.

The following function uses the countDocuments() method.

router.route("/countDocuments").get(function(req, res) {
  detail.countDocuments({}, function(err, result) {
    if (err) {
      console.log(err);
    } else {
      res.json("Number of documents in the collection: " + result);
    }
  });
});

The output is – “Number of documents in the collection: 5”. It returns the total number of documents as we are passing an empty object only.

Let’s use the estimatedDocumentCount() method.

router.route("/countDocuments").get(function(req, res) {
  detail.estimatedDocumentCount({}, function(err, result) {
    if (err) {
      console.log(err);
    } else {
      res.json("Number of documents in the collection: " + result);
    }
  });
});

The output will be the same – “Number of documents in the collection: 5”. Here, we are again passing an empty object. But what will happen if we put a filter in both the methods? The countDocuments will return the count of documents according to the filter, but the estimatedDocumentCount() will still return the total number of documents present in the collection. It will ignore the filter.

Conclusion

The count() method is useful for counting the number of documents in a collection. But it is deprecated now and we have two other methods – countDocuments() and estimatedDocumentCount(). The countDocuments() method returns the number of documents in the collection and accepts a filter also. But the estimatedDocumentCount does not accept a filter. The estimatedDocumentCount() method is useful when there is a large number of documents in a collection. It is fast as compared to the countDocuments() method.

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.