[英]Aggregate group inside group in MongoDB
通過aggregate
我可以按以下方式檢索按天分組的所有數據:
db.collection('checkpoint').aggregate
[
{ '$match': {'id_journey': journey.id_journey} },
{ '$sort': { 'when': 1} },
{
'$group': {
'_id': { $dateToString: { format: '%Y-%m-%d', date: '$when' } },
'day': {
'$push': {
'id': '$id_checkpoint',
'when': '$when',
'type': '$type',
'url_media': '$url_media'
}
}
}
},
{ '$sort': { '_id': 1 } },
{
'$project': {
'_id': 1,
'day': 1
}
}
], function(err, result) {
res.json(result);
});
結果是:
[{
_id: "2016-04-22",
day: [{
id: "c571be034449bee845f2b43211",
when: "2016-04-22T20:51:00.190Z",
type: "picture",
url_media: "my_photo_1.jpg"
}]
}, {
_id: "2016-04-23",
day: [{
id: "c571be034449bee845f2b43222",
when: "2016-04-23T20:50:00.190Z",
type: "picture",
url_media: "my_photo_2.jpg"
}, {
id: "c571be034449bee845f2b43233",
when: "2016-04-23T20:51:00.190Z",
type: "picture",
url_media: "my_photo_3.jpg"
}]
}]
沒錯
但是,如果我需要每天在一個$hour
分組一次(使用MongoDB的$hour
Date Aggregation Operators ),該怎么辦? 想要的結果是將每個日組細分為幾個小時組:可以嗎?
是的,你可以做到。 首先,您必須計划小時。 現在,您在聚合管道中有了小時字段。 您可以輕松地在小時字段上分組
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.