MongoDB

MongoDB Count Function

The count() function is provided by MongoDB to count the number of the given documents from the collection that meets the specified condition. The count() method in general takes two arguments. The first one is the conditional statement and the second one is optional. This method produces a numeric count of the documents that match the criteria. The count() function is more convenient to find the number of documents in a large document collection rather than displaying all of the data.

How to Use the Count Function in MongoDB?

We have two ways to use the count() function in MongoDB. First, simply invoke the $count function on the collection like this: “db.collection_name.count()”. The next one is to call the count() function after employing the find() function. The count() method takes the parameter which is the selection criteria. But when the find() method is used with the count() method then selection criteria are given to the find() method, it does not specify any parameter. Consider the following query of inserting documents in the collection “WinterItems”. We are going to work with this collection to implement the count() function on it.

db.WinterItems.insertMany([
      {
          "_id": 01,
          "Item": "Hoodie",
          "Price": 500,
          "Discount": "20%",
          "Colors" : ["Green", "Black", "Yellow"]
      },
      {
          "_id": 02,
          "Item": "Sweater",
          "Price": 700,
          "Discount": "40%",
          "Colors" : ["Pink", "White", "Brown"]
      },
      {
          "_id": 03,
          "Item": "Jackets",
          "Price": 900,
          "Discount": "30%",
          "Colors" : ["Yellow", "Maroon", "Blue"]
      },
      {          
         "_id": 04,
          "Item": "Gloves",
          "Price": 200,
          "Discount": "10%",
          "Colors" : ["Black", "white", "Purple"]
              },

      {
          "_id": 05,
          "Item": "Socks",
          "Price": 100,
          "Discount": "5%",
          "Colors" : ["Red", "Black", "Peach"]
          }
  ])

As shown, the documents have been correctly inserted into the collection “WinterItems”.

Example # 1: Using the $count Function in MongoDB.

Now, we have implemented the count() function which will count all the documents inserted in the collection “WinterItems”. Here, the count() function does not contain any parameter. Although, we have not used the find() method before.

db.WinterItems.count()

The count() method gives the numeric value “5”, which represents the number of documents in the specified collection.

Example # 2: Using the Count Function in MongoDB for a Single Field.

As discussed earlier, we can use the find() method which will be specified with the condition for the count() function. Here, we have given a count() function query where we have used the find() method to provide the expression. We have passed the expression “item: Jackets” to the find() method. The find() method searched for the value “Jackets” associated with the field “item”. After that, we deployed the count() method which counts the number of documents whose field “item” has the value “Jackets”.

db.WinterItems.find({"Item":"Jackets"}).count()

Only one document is present in the collection whose item value is “Jackets” which is why the count() method generates the number value “1”.

Example # 3: Using the Count Function in MongoDB with the Condition.

We have used the count() function to acquire the document that satisfies the condition given as a parameter. Here, we have simply called the count() function which takes the expression “_id:{$gt:03}”. We have used the conditional operator “$gt” to get the specified value. We intend to count the documents where the “_id” field has a value larger than “03”.

db.WinterItems.count({"_id":{$gt:03}})

The result displayed that we have two documents in the collection whose “_id” is greater than “3”.

Example # 4: Using the Count Function in MongoDB for Multiple Fields.

The count() function takes more than one expression to match all the documents. Here, we have set the expression for the count() function in a find() method. The find() method is provided with the expressions “{ “Item”: “Gloves”} and {“Colors”: [“Black”, “white”, “Purple”] }”. The field “Items” searches for the value “Gloves” and the field “Colors” finds the value from the array which is equal to the colors “Black”, “white”, and “Purple”. When these expressions are matched with the documents then, the count() function counts those documents and gives the integer value.

db.WinterItems.find( { "Item": "Gloves", "Colors": ["Black", "white", "Purple"] } ).count();

The count() method returns the value “1” which indicates that only one document fulfills the specified criteria.

Example # 5: Using the Count Function in MongoDB with the readConcern Parameter.

The count() function has various optional parameters which can be used when required. Here, we are using the “readConcern” as an optional parameter in the count() function. We have used runCommand to specify the query of the count() function. Then, we deployed the count() function which is provided with the collection name “WinterItems” and we used the keyword “query” to which the expression is passed. The expression “{ price: { $lt: 500 } }” is used to get a document whose price is less than “500”. After that, we defined the readConcern parameter which further set the “level” with the “local” option to display the result.

db.runCommand( { count:'WinterItems', query: { price: { $lt: 500 } }, readConcern: { level: "local" } } )

The readConcern parameter of the count() function is used to represent the results in the following way:

Example # 6: Using the Count Function in MongoDB with the Skip Method.

The skip() method is used here before the count() method to skip the number of the document which satisfies the conditions. We have given a query where the find() method is used to pass the expression “{“Item”: “Socks”}”. When the expression is matched with the document, then the skip() method is called. The skip() method takes the parameter value “1” to only skip the one document which appears at first. Then, the leftover documents are then counted using the count() function.

db.WinterItems.find({"Item":"Socks"}).skip(1).count()

Note that the value “0” is obtained from the count() function because only one document meets the expression which is already skipped by the skip() method.

Example # 8: Using the Count Function Within the $group Function in MongoDB.

The aggregate() method is also used to count many fields by employing the $count operator inside it. Here, we have called the $count operator within the $group operator of the aggregation method which groups the results in the form of a set. Here, we have provided the field “_id” which is equal to “4” and also invoked the $count operator which is specified with no expression. Then, $count counts all the documents and displays it in the shell along with the given value of the key “_id”.

db.WinterItems.aggregate([
  {
    $group: {
      _id: "04",
      count: {
        $count: {}
      }
    }
  }
])

We have a result that is obtained in the form of a group. The result generates the “_id: 4” and the count value “5” which is the total number of documents.

Conclusion

The MongoDB count function is explored in this guide. The count() function in MongoDB is used to figure out how many documents are in a collection according to condition. We have provided various queries for the count() function. We have also used the optional parameter of the count() method to generate the results. Further, we used the count() function as the $count operator for aggregation purposes.

About the author

Saeed Raza

Hello geeks! I am here to guide you about your tech-related issues. My expertise revolves around Linux, Databases & Programming. Additionally, I am practicing law in Pakistan. Cheers to all of you.