Jane
Jane

Reputation: 109

mongoDB aggregation: how to use value as key

Hi I've got some records like:

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

can I get the dict below by using aggregate?

{user:1,{A:1,B:3}, user:2,{A:5,B:2}}

Upvotes: 6

Views: 4136

Answers (1)

Senthur Deva
Senthur Deva

Reputation: 787

You can use this $group $arrayToObject

db.col.aggregate([
   {"$group" : {"_id" : "$user","data" : {"$push" : {"k" : "$item","v" : "$count"}}}},
   { "$project" : {"user" : "$_id","_id" : 0, "data" : { "$arrayToObject" : "$data" }}}

])

Upvotes: 5

Related Questions