【发布时间】:2017-03-09 06:01:39
【问题描述】:
我在 MongoDB 数据库中有很多文档,看起来像以下四个文档(注意前 3 个是 2017 年 2 月,最后一个是 2017 年 3 月):
{"_id": 0,
"date": ISODate("2017-02-01T00:00:00Z),
"item": "Basketball",
"category": "Sports"}
{"_id": 1,
"date": ISODate("2017-02-13T00:00:00Z),
"item": "Football",
"category": "Sports"}
{"_id": 2,
"date": ISODate("2017-02-22T00:00:00Z),
"item": "Massage",
"category": "Leisure"}
{"_id": 3,
"date": ISODate("2017-03-05T00:00:00Z),
"item": "Golf club",
"category": "Sports"}
我正在尝试按 MONTH/YEAR 对项目进行分组,并在其中按 CATEGORY 对项目进行分组。因此,对于上面的四个文档,聚合管道应该返回如下所示的内容:
{"_id": {
"month": 2,
"year": 2017
},
"data": [
{"category": "Sports",
"items": ["Basketball", "Football"]
},
{"category": "Leisure",
"items": ["Massage"]
}
]
},
{"_id": {
"month": 3,
"year": 2017
},
"data": [
{"category": "Sports",
"items": ["Golf Club"]
}
]
}
我还希望返回的光标按年作为主要排序,月份作为次要排序。
【问题讨论】:
标签: mongodb aggregation-framework pymongo