mongodb – Aggregation – Count

How do you get the number of Debit and Credit transactions? One way to do it is by using count() function as below.

> db.transactions.count({cr_dr : "D"});

or

> db.transactions.find({cr_dr : "D"}).length();

But what if you do not know the possible values of cr_dr upfront. Here Aggregation framework comes to play. See the below Aggregate query.

> db.transactions.aggregate( 
      [
          {
              $group : {
                  _id : '$cr_dr', // group by type of transaction
                // Add 1 for each document to the count for this type of transaction
                  count : {$sum : 1}
              }
          }
      ]
  );

And the result is

{
    "_id" : "C",
    "count" : 3
}
{
    "_id" : "D",
    "count" : 5
}

if you want to reproduce, please indicate the source:
mongodb – Aggregation – Count - CodeDay