2016-01-08 87 views
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的聚合框架做服务器端不做处理,让它可以在数据库方面做了什么?

+0

看起来像您需要的项目步骤之后使用[$组(https://docs.mongodb.org/manual/reference/operator/aggregation/group/)运算符 – saljuama

+0

我不知道一吨左右的MongoDB,但似乎为$组和$地图聚合运营商: https://docs.mongodb.org/manual/reference/operator/aggregation/map/ HTTPS:/ /docs.mongodb.org/manual/reference/operator/aggregation/group/ – Vinay

回答

1

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


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

}

参考here

+0

谢谢!这就是我需要的 – Abdizriel