1

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
  }
}
0

1 Answer 1

5

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"}
    }}
]);
Sign up to request clarification or add additional context in comments.

2 Comments

I have updated the question. I think your query is correct but to acquire the above result, I will need to query four times for four timestamps. Is there a way to get the above result in one query?
I don't know if there is a solution, I never group by date with mongo, try to $match in term of your need

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.