| by Arround The Web | No comments

How to Count Documents with MongoDB Aggregate Count

As the name suggests, the $count aggregation in MongoDB must be utilized for counting field records. One of the popular ways to count records is to use the count() method. Additionally, certain aggregation operators let you count records brought in from a preceding stage of the aggregate pipeline. Within this guide today, we will be discussing the count aggregation of MongoDB using code examples.

Example 01

To perform the $count operation on the fields of a database collection in MongoDB, we need to have numerous records. Therefore, we created a collection named “Test” and inserted 12 records into it simultaneously using the insertMany() function. Now, the records of this “Test” collection have been displayed on the MongoDB shell via the find() function query. You can see that it has a total of three fields:_id, name, and score.

test> db.Test.find({})

Now, to apply the $count stage on any field, we must use MongoDB’s aggregate function within the “db” instruction. The aggregate function consists of the condition statement, often using the $match operator on a specific field, followed by a new field that displays the total count obtained from the specified condition field using the $count operator.

In our case, we have been employing the $match operator to search for the matching records for the value “60” in the score field, while the $count operator has been used to count the total number of records fetched and display them under the new field named “SameScore”. The output for this query has been showing a field ‘SameScore” with the value “2” indicating that there are two records with the “score” value “60” is 2 in the collection “Test”.

db.Test.aggregate([ { $match: { "score": 60 } }, { $count: "SameScore" } ])

You can also use the $count aggregation to count the fields other than numbers, such as the “name” field of the Test collection. We have been using match aggregation to search for the record in the collection where the name field has the value “John”. The count aggregation has successfully counted the total number of records matched which is 2.

db.Test.aggregate([ { $match: { "name": "John" } }, { $count: "SameName" } ])

Example 02

Let’s update the above query and apply another condition to get different records. This time, we will be applying the $match aggregation of the score field to get the total count of records where the score field has a value of less than 30. The count aggregation will be counting the total number of records and adding to a new column “GradeD.” The output shows the result “2” as the count number for the matched value.

db.Test.aggregate( [ { $match: { score: { $lt: 30 } } }, { $count: "GradeD" } ] )

You can also use the $count aggregation while applying the logical operators to perform more than 1 condition on the field records. Therefore, a total of two conditions have been applied to the “Score” field using the $and operator: gte (greater than or equal to) and lte (less than and equal to). Both conditions must be true to get the result and count its records. The total count shows there are five records with the matching criteria.

db.Test.aggregate( [ { $match: { "$and": [ {"score": {$gte: 60}}, {"score": {$lte: 80}} ] }},

{ $count: "GradeB" } ] )

Example 03

In the above illustrations, we have used the count aggregation to only get the number of matched records for the particular field values, such as a specified score or name. The aggregation method of MongoDB allows you to get the count number of all the records containing duplicate values in the collection.

For this, you need to use the $group aggregation within the aggregate function command, as below. The field _id has been used to specify the “name” field on which the count aggregation would work. Along with this, the NameCount user-defined field will utilize the $count aggregation to count several duplicates in the “name” field.

The output for this query has been displayed beneath. It contains the values from the “name” field and their count number within the NameCount field according to duplications of values, such as Cillian having 4 duplicates, and so on.

db.Test.aggregate([ { $group: { _id: '$name', NameCount: { $count: {} }, }, }, ])

Example 04

We can also use the count aggregation on nested field records to count particular field values. To elaborate on this, we have created a collection named “Teacher” and added nested field “sub” and array-type field “shift” within it along with other fields: name and pay. The find() function has been displaying all five records of this collection.

test> db.Teacher.find({})

Now, we have applied the aggregate function containing the match operator. Also, the $and operator have been applied to the sub-field “math” of the “sub” field, which contains two different conditions. The count has been then calculated. The output shows there are two records where the subfield math has greater than 10 and less than 20 values.

db.Teacher.aggregate( [ { $match: { "$and": [ {"sub.math": {$gte: 10}}, {"sub.math": {$lte: 20}} ] }}, { $count: "GradeA" } ] )

Example 05

Let’s look at the last example to illustrate using the count() function this time instead of using the count aggregation. So, the count() function has been applied to the array-type field of the “Teacher” collection i.e. “shift”. Using the indexes for the array field using index 2, we have specified the matching criteria as “night”. It outputs “2” as the total number of counts for the entry “night”.

db.Teacher.count({ "shift.2": "night" })

In a very similar way, the count() function can also be applied to the nested fields, such as the subfield “phy” of the “sub” field from the collection “Teacher”. We have specified the matching criteria using the “lte” operator indicating values less than 14 in the “phy” subfield. The output of this instruction has been displaying “2” i.e. 4 records with a value less than 14.

db.Teacher.count( { "sub.phy": { $lte: 14 } })

Conclusion

This guide has been demonstrating and elaborating on using $count aggregation of MongoDB with several code examples. The examples include the implication of count aggregation to fetch the count number for specific value records and all the field records through the collections. Also, it includes the use of count aggregation on array fields and embedded (nested) fields. In the end, the count() function example has been included to make a difference between the use of count aggregation and the count function.

Share Button

Source: linuxhint.com

Leave a Reply