2017-03-08 12 views
-1

私は、次の4つの文書(最初の3が2017年2月で、最後の1は、2017年3月であることに注意)のように見えるのMongoDBデータベース内に多くの文書があります。MongoDBの集計:日付グループ内のグループ化データ

{"_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"] 
    } 
] 
} 

私も返さカーソルになりたい:だから集約パイプラインは、上記の4つのドキュメントのために、このようなものを返す必要があります。

答えて

0

それを実演しました。 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) 
関連する問題