嗨,我有一些类似的记录:
{_id:xxx, user:1, item:A, count: 1}
{_id:xxx, user:1, item:B, count: 3}
{_id:xxx, user:2, item:A, count: 5}
{_id:xxx, user:2, item:B, count: 2}
我可以通过使用聚合来获取下面的字典吗?
{user:1,{A:1,B:3}, user:2,{A:5,B:2}}
答案 0 :(得分:1)
您可以使用此$group $arrayToObject
db.col.aggregate([
{"$group" : {"_id" : "$user","data" : {"$push" : {"k" : "$item","v" : "$count"}}}},
{ "$project" : {"user" : "$_id","_id" : 0, "data" : { "$arrayToObject" : "$data" }}}
])