【问题标题】:MongoDB return flatten resultMongoDB 返回展平结果
【发布时间】:2016-04-12 14:21:11
【问题描述】:

我的 MongoDB 中有一些嵌套集合。

当我在我的服务器上运行以下查询时:

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

我在这里得到这个结果:

[
{
  "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
}
]

现在,这就是我想要的:

[
{
  "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]
}
]

我可以通过将我的服务器端函数更改为:

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();
});

有没有办法只使用 MongoDB 聚合框架而不在服务器端进行处理而让它在 db 端完成?

【问题讨论】:

标签: javascript node.js mongodb


【解决方案1】:

对于您使用的管道,请在末尾再扩展一个管道运算符,如下所示。


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

}

参考here

【讨论】:

  • 谢谢!这就是我需要的
猜你喜欢
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2018-05-09
  • 2012-10-28
  • 1970-01-01
  • 2012-07-26
  • 2021-09-20
  • 1970-01-01
相关资源
最近更新 更多