我的 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 聚合框架来实现相同的目的,而不是在服务器端进行处理并让其在数据库端完成?
最佳答案
对于您使用的管道,请在末尾再扩展一个管道运算符,如下所示。
$group: {
_id: '$date',
types: {$push: '$type'},
counts: {$push: '$count'}
}
引用here
关于javascript - MongoDB 返回扁平化结果,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/34667934/