【发布时间】: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 端完成?
【问题讨论】:
-
看起来您需要在项目步骤之后使用$group 运算符
-
我不太了解 mongodb,但似乎有 $group 和 $map 聚合运算符:docs.mongodb.org/manual/reference/operator/aggregation/mapdocs.mongodb.org/manual/reference/operator/aggregation/group
标签: javascript node.js mongodb