Roman Roman
Roman Roman

Reputation: 917

How to customize $group output in MongoDB?

After applying $group stage I get the following result:

[
    { 
        _id: { month: 7, day: 19, year: 2018 },
         count: 4 
    }
]

Is it possible to apply some another stage and get output like:

[
    {
        date: '7-19-2018',
        count: 4
    }
]

Upvotes: 2

Views: 54

Answers (1)

s7vr
s7vr

Reputation: 75964

You can use $dateFromParts to convert the date parts into date followed by $dateToString to convert it to string in 3.6.

Something like

{"$project":{
  "_id":0,
  "date":{
    "$dateToString":{
      "format":"%m-%d-%Y",
      "date":{"$dateFromParts":{"year":"$_id.year","month":"$_id.month","day":"$_id.day"}}
    }
  },
  "count":1
}}

Upvotes: 1

Related Questions