I have a 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 to find the count for each genre for each user i.e. my ideal final result would be something like this :
1 | comedy |2
1 | action |1
1 | thriller |1
2 | war |2
2 | adventure |1
2 | thriller |1
Any helps would be really useful.
you can do this with aggregation using $group
try this :
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 }
Collected from the Internet
Please contact [email protected] to delete if infringement.
Comments