NitinD
NitinD

Reputation: 499

Get multiple counts based on multiple conditions in MongoDB

I wanna run multiple queries to get the count on a MongoDB collection. Like, I wanna run a query to find out pending status users and completed status users. Something like this, is there a way to write these two conditions in a query/aggregation and get the separate results in MongoDB?

My Requirement is,

I need to get the count of the user of status pending, completed and open for Today, Yesterday, last week and last Month.

I need different status count like this,

{
 "today": {
    "pending": 10,
    "completed": 13,
    "open": 5
  },
  "yesterday": {
    "pending": 10,
    "completed": 13,
    "open": 5
  },
  "lastWeek": {
    "pending": 10,
    "completed": 13,
    "open": 5
  },
  "lastMonth": {
    "pending": 10,
    "completed": 13,
    "open": 5
  }
}

Upvotes: 1

Views: 1509

Answers (1)

Nicolas
Nicolas

Reputation: 457

You can use the aggregation $group stage for that:

db.Collection.aggregate([
    {$project: {
        // If your pending/completed field is set to 1 or true
        pending: {$cond: [{$eq: ["$pending", 1 /* or true */]}, 1, 0]},
        completed: {$cond: [{$eq: ["$completed", 1 /* or true */]}, 1, 0]}
    }},
    {$group: {
        _id: //what you want,
        pending: {$sum: "$pending"},
        completed: {$sum: "$completed"}
    }}
]);

Upvotes: 5

Related Questions