Wednesday, 10 May 2017

How can I combine year month day to a ISODate in mongoose a aggregation

I have the following aggregation ran under mongoose:

[{
        $match: {
            subject: "page",
            event: "view",
            page: new ObjectId(req.params.id)
        }
    }, {
        $group: {
            _id: {
                page: req.params.id,
                tracker: "$tracker",
                year: {
                    $year: "$time"
                },
                month: {
                    $month: "$time"
                },
                day: {
                    $dayOfMonth: "$time"
                }
            },
            count: {
                $sum: 1
            }
        }
    }, {
        $project: {
            _id: false,
            year: "$_id.year",
            month: "$_id.month",
            day: "$_id.day",
            count: true
        }
    }]

I get the following document array as output:

[
  {
    "count": 1,
    "year": 2017,
    "month": 2,
    "day": 22
  },
  {
    "count": 2,
    "year": 2017,
    "month": 2,
    "day": 17
  },
  ...
]

How can I make a projection like this (while staying in the aggregation loop):

[
  {
    "count": 1,
    "date": 2016-03-22 00:00:00.000Z
  },
  ...
]

I have read through most of the Date and String aggregation operators but I haven't found anything can could achieve this. Thanks!



via Maxime Asselin

No comments:

Post a Comment