mongodb count value of one field based on other -
i have collection named genre_collection of following structure :
user | genres ---------------- 1 | comedy 1 | action 1 | thriller 1 | comedy 1 | action 2 | war 2 | adventure 2 | war 2 | thriller
i'm trying find count each genre each user i.e. ideal final result :
1 | comedy |2 1 | action |1 1 | thriller |1 2 | war |2 2 | adventure |1 2 | thriller |1
any helps useful.
you can aggregation using $group
try :
db.genre_collection.aggregate([ { $group:{ _id:{ genre:"$genres", user:"$user" }, count:{ $sum:1 } } } ])
output:
{ "_id" : { "genre" : "adventure", "user" : 2 }, "count" : 1 } { "_id" : { "genre" : "action", "user" : 1 }, "count" : 2 } { "_id" : { "genre" : "thriller", "user" : 2 }, "count" : 1 } { "_id" : { "genre" : "war", "user" : 2 }, "count" : 2 } { "_id" : { "genre" : "comedy", "user" : 1 }, "count" : 2 } { "_id" : { "genre" : "thriller", "user" : 1 }, "count" : 1 }
Comments
Post a Comment