MongoDB Aggregation Framework - $count stage

💧 $count stage:

The $count stage is used to count the number of input documents. The $count stage will always be the last one.

We can get the number of output documents from the last stage.

db.persons.aggregate([

{$group: {_id: {age: "$age", eyeColor: "$eyeColor"}}},

{$count: "allDocument"}

])


Output: 

"allDocument" : NumberInt(63) }


💧 Other methods of the $count stage:

👉 toArray() method with length:

db.persons.aggregate([]).toArray().length;

i.e; the slow method

👉 itcount():

db.persons.aggregate([]).itcount();

i.e; the slow method

👉 count() with find():

db.persons.find({}).count();


use either find({}).count(); or. $count stage because they are fast.


Example:

db.persons.aggregate([

{$match: {age: {$gte: 25}}},

        {$group: {_id: {age: "$age", color: "$eyeColor"}}},

        {$count: "countAge"}        

]);


Output: 

 "countAge": NumberInt(48) }

Post a Comment

Previous Post Next Post