lolalola
lolalola

Reputation: 3823

MongoDB (v3) aggregate and count all rows

i need group all users by age and then need count all rows.

db.users.aggregate({
    $group : {_id : "$age"}
    }
);

I have read MongoDb documentation, but don't get how working count and aggregate together.

Upvotes: 0

Views: 524

Answers (2)

Isaiah4110
Isaiah4110

Reputation: 10090

You should be able to do this within a single group query:

db.users.aggregate([{$group:{_id:"$age",count:{$sum:1}}]);

Upvotes: 0

Volodymyr Synytskyi
Volodymyr Synytskyi

Reputation: 4055

You can group all your grouped data by age together and use aggregational $sum for counting all rows from the grouped data:

db.users.aggregate([
  {
    $group : { _id : "$age" }
  },
  {  
    $group : {
      _id : null,
      count: { $sum: 1 }
    }
  }
]);

Upvotes: 1

Related Questions