Sujeet Kumar
Sujeet Kumar

Reputation: 1320

MongoDB group by count based on condition

I have the below mongo DB schema:

 {
    "_id" : "5b76c3c037548390fdb5b40e",
    "userId" : "4601",
    "modified" : ISODate("2018-08-21T19:13:43.301+05:30"),
    "rStatus" : "started",
},
{
    "_id" : "5b76c3c037548390fdb5b40e",
    "userId" : "13",
    "modified" : ISODate("2018-08-21T19:13:43.301+05:30"),
    "rStatus" : "completed",
},
........

There is a need to get data group by modified date and count of rStatus field, eg

{
    modified:"2018-08-21",
    count :{"completed":1,"ongoing":4}
},
{
    modified:"2018-07-23",
    count :{"completed":2,"ongoing":5}
},

I am using $group but its count by modified date only not by the inner keys' values.

Upvotes: 0

Views: 4116

Answers (1)

s7vr
s7vr

Reputation: 75964

You can use below aggregation in 3.6.

db.colname.aggregate([
{"$group":{
  "_id":{
    "date":{"$dateToString":{"date":"$modified","format":"%Y-%m-%d"}},
    "rstatus":"$rStatus"
  },
  "count":{"$sum":1}
}},
{"$group":{
  "_id":"$_id.date",
  "count":{"$mergeObjects":{"$arrayToObject":[[["$_id.rstatus","$count"]]]}}
}}])

Upvotes: 5

Related Questions