【问题标题】:MongoDB Aggregation: grouping data within date groupsMongoDB聚合:在日期组内分组数据
【发布时间】: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


    【解决方案1】:

    想通了。这是使用 pymongo api 的答案:

    from bson.son import SON
    
    cursor = db.collection.aggregate([
      {'$group': {
        '_id': {'month': {'$month': '$date'},
                'year': {'$year': '$date'},
                '$category': '$category'},
        'items': {'$push': '$item'}
      }},
      {'$group': {
        '_id': {'month': '_id.month',
                'year': '_id.year'}
        'data': {
          '$push': {
            'category': '$_id.category',
            'items': '$items'
          }
        }
      }},
      {'$sort': SON([('_id.year', 1), ('_id.month', 1)])}
    ])
    my_data = list(cursor)
    

    【讨论】:

      猜你喜欢
      • 2013-11-25
      • 2019-05-17
      • 1970-01-01
      • 2021-07-16
      • 1970-01-01
      • 1970-01-01
      • 2019-04-01
      • 2021-09-28
      • 1970-01-01
      相关资源
      最近更新 更多