0

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.

SuleymanSah
  • 17,153
  • 5
  • 33
  • 54
Sujeet Kumar
  • 1,280
  • 1
  • 17
  • 25
  • 1
    this might be the answer `db.collection.aggregate([ { "$group": { "_id": { "$dateToString": { "date": "$modified", "format": "%Y-%m-%d" }}, "completed": { "$sum": { "$cond": [{ "$eq": [ "$rStatus", "completed" ] }, 1, 0 ] }} }} ])` – Ashh Sep 06 '18 at 10:51
  • 1
    @AnthonyWinzlet, Thanks, Its working – Sujeet Kumar Sep 09 '18 at 08:25

1 Answers1

5

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"]]]}}
}}])
s7vr
  • 73,656
  • 11
  • 106
  • 127