How to use Node JS and mongodb to Query Count

Introduction

In this article we’ll be covering how to find the number of documents of a MongoDB collection. Specifically we will be using Node JS and MongoDB to query the count of a collection.

There can be multiple MongoDB databases. Each database can contain several collections and each of these collections can contain hundreds of documents. Keeping count of these documents can be frustrating. The number of documents can increase or decrease at any time. MongoDB provides three methods for counting documents. These methods are count(), countDocuments(), and estimatedDocumentCount(). The count() method was the primary method for counting documents, but it is deprecated now. In this article, we will discuss the count() method as well as the other two methods in mongoose and nodejs.

For demonstration purposes we will use the details collection which you can see below:

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
{ "_id" : ObjectId("5e15bc5aa7b6505cd15e809a"), "name" : "John", "age" : 21, "location" : "New York" }
{ "_id" : ObjectId("5e15bc69a7b6505cd15e809b"), "name" : "Sam", "age" : 24, "location" : "Texas" }
{ "_id" : ObjectId("5e15bda5a7b6505cd15e809c"), "name" : "Lisa", "age" : 27, "location" : "Chicago" }
{ "_id" : ObjectId("5e15bdaba7b6505cd15e809d"), "name" : "Max", "age" : 25, "location" : "Chicago" }
{ "_id" : ObjectId("5e15bdb5a7b6505cd15e809e"), "name" : "Joe", "age" : 29, "location" : "Texas" }
{ "_id" : ObjectId("5e15bdc4a7b6505cd15e809f"), "name" : "Sunny", "age" : 23, "location" : "Detroit" }
{ "_id" : ObjectId("5e15bdd2a7b6505cd15e80a0"), "name" : "Maxine", "age" : 31, "location" : "New York" }
{ "_id" : ObjectId("5e15bddca7b6505cd15e80a1"), "name" : "Lily", "age" : 26, "location" : "New York" }
{ "_id" : ObjectId("5e15bdefa7b6505cd15e80a2"), "name" : "Ronn", "age" : 36, "location" : "Chicago" }
{ "_id" : ObjectId("5e15be04a7b6505cd15e80a3"), "name" : "Ell", "age" : 22, "location" : "New York" }
{ "_id" : ObjectId("5e15be11a7b6505cd15e80a4"), "name" : "Kenn", "age" : 28, "location" : "Detroit" }
{ "_id" : ObjectId("5e15be21a7b6505cd15e80a5"), "name" : "Ben", "age" : 25, "location" : "New York" }
{ "_id" : ObjectId("5e15be32a7b6505cd15e80a6"), "name" : "Giya", "age" : 34, "location" : "Texas" }
{ "_id" : ObjectId("5e15be44a7b6505cd15e80a7"), "name" : "Sammy", "age" : 31, "location" : "New York" }
{ "_id" : ObjectId("5e15be5ba7b6505cd15e80a8"), "name" : "Brock", "age" : 38, "location" : "Detroit" }
{ "_id" : ObjectId("5e15be69a7b6505cd15e80a9"), "name" : "Gwen", "age" : 38, "location" : "New York" }
{ "_id" : ObjectId("5e15be9aa7b6505cd15e80aa"), "name" : "Lemmy", "age" : 28, "location" : "Chicago" }
{ "_id" : ObjectId("5e15beaaa7b6505cd15e80ab"), "name" : "James", "age" : 23, "location" : "Texas" }
{ "_id" : ObjectId("5e15beb7a7b6505cd15e80ac"), "name" : "Jimmy", "age" : 29, "location" : "New York" }
{ "_id" : ObjectId("5e15becda7b6505cd15e80ad"), "name" : "Pep", "age" : 21, "location" : "Detroit" }

There are several documents in this collection. We will use the postman tool for endpoint testing. You can download this tool from www.getpostman.com.

count()

So let’s start with the count() method. The following route handler will be invoked when the endpoint ‘/countDocuments’ will be executed. NOTE We have used the popular ‘express’ package for Node JS to simplify the creation of our routes.

1
router.route("/countDocuments").get(function(req, res) {});

Let’s call the count() method on the details collection.

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
router.route('/countDocuments').get(function(req,res){

    details.count( {}, function(err, result){

        if(err){
            res.send(err)
        }
        else{
            res.json(result)
        }

   })


})

Currently, we are passing an empty object as a query. Let’s execute this route using postman and see what it returns.

Image from Gyazo

It returns the total number of documents in the details collection, i.e. 20. Let’s make some changes and count how many documents are present in the details collection where the value of the location field is “New York”.

1
2
3
4
5
6
7
8
9
router.route("/countDocuments").get(function(req, res) {
  details.count({ location: "New York" }, function(err, result) {
    if (err) {
      res.send(err);
    } else {
      res.json(result);
    }
  });
});

Image from Gyazo

There are 8 documents where the value of the location field is “New York”. But this method is deprecated and it will be removed in the future.

Image from Gyazo

This warning appears when the count() method is used. Let’s discuss what are these two methods.

countDocuments() vs 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.

So if you need to count the total number of documents in a huge collection, go for estimatedDocumentCount(), or you can choose countDocuments() method as well. But if you need to count the number of documents according to a particular condition, go for countDocuments(). You may choose the count() method but it will be removed in the future causing trouble in your code.

Conclusion

Thank you for joining us for another Object Rocket knowledge base tutorial. We hope you feel more informed on how to count documents in a collection using the count(), countDocuments(), and estimatedDocumentCount() functions.

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.