0
我在MongoDB中有幾個嵌套集合。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的聚合框架做服務器端不做處理,讓它可以在數據庫方面做了什麼?
看起來像您需要的項目步驟之後使用[$組(https://docs.mongodb.org/manual/reference/operator/aggregation/group/)運算符 – saljuama
我不知道一噸左右的MongoDB,但似乎爲$組和$地圖聚合運營商: https://docs.mongodb.org/manual/reference/operator/aggregation/map/ HTTPS:/ /docs.mongodb.org/manual/reference/operator/aggregation/group/ – Vinay