Ad

MongoDB Return Flatten Result

- 1 answer

I have a few nested collections in my MongoDB.

When I run the following query on my server:

AggregatedData
.aggregateAsync([{
  $match: {
    "_id.date": {
      $gte: dateFrom,
      $lte: dateTo
    }
  }
}, {
  $project: {
    "date": "$_id.date",
    "type": "$_id.type",
    "count": "$count.total",
    "_id": 0
  }
}]);

I end up with this result here:

[
{
  "date": "2016-01-08T00:00:00.000Z",
  "type": "V1",
  "count": 7359
},
{
  "date": "2016-01-08T00:00:00.000Z",
  "type": "V2",
  "count": 2874
},
{
  "date": "2016-01-08T00:00:00.000Z",
  "type": "V3",
  "count": 512
},
{
  "date": "2016-01-07T00:00:00.000Z",
  "type": "V1",
  "count": 6892
},
{
  "date": "2016-01-07T00:00:00.000Z",
  "type": "V2",
  "count": 3124
},
{
  "date": "2016-01-07T00:00:00.000Z",
  "type": "V3",
  "count": 457
}
]

Now, this is what I want:

[
{
  "date": "Thu Jan 07 2016 00:00:0 GMT-0800 (PST)",
  "types": ["V1", "V2", "V3"],
  "values": [7359, 2874, 512]
},
{
  "date": "Thu Jan 08 2016 00:00:0 GMT-0800 (PST)",
  "types": ["V1", "V2", "V3"],
  "values": [6892, 3124, 457]
}
]

I can achieve that by changing my server-side function to this:

AggregatedData
.aggregateAsync([{
  $match: {
    "_id.date": {
      $gte: dateFrom,
      $lte: dateTo
    }
  }
}, {
  $project: {
    "date": "$_id.date",
    "type": "$_id.type",
    "count": "$count.total",
    "_id": 0
  }
}])
.then((results) => {
  return _.chain(results)
    .groupBy('date')
    .map(function(value, key) {
      return {
        date: key,
        types: _.pluck(value, 'type'),
        values: _.pluck(value, 'count')
      }
    })
    .value();
});

Is there a way to achieve the same using just MongoDB aggregation framework to don't doing processing on server-side and let it be done on db side?

Ad

Answer

For the pipeline you have used, extend it by one more pipeline operator at the end as below.


$group: {
    _id: '$date',
    types: {$push: '$type'},
    counts: {$push: '$count'}

}

refer here

Ad
source: stackoverflow.com
Ad