I have a user collection with sub document of 'music' that has a sub document of 'likes'. I'll like to run a search and find the top 10 users who liked a specific artist the most, sorted by how much they liked them. this is how the dataset is structured
[
{
'_id' : ObjectId("507f1f77bcf86cd799439011"),
'user_name' : "John",
'music' : [
'likes' [
{'name': 'david bowie', 'strength': 50 },
{'name': 'john lennon', 'strength': 100 },
{'name': 'bob marley', 'strength': 20 },
]
]
},
{
'_id' : ObjectId("54304264e77cc5a1670cb318"),
'user_name' : "Paul",
'music' : [
'likes' [
{'name': 'david bowie', 'strength': 60 },
{'name': 'john lennon', 'strength': 70 },
{'name': 'bob marley', 'strength': 100 },
]
]
}
]
I've been trying to use the following aggregate command:
$artist = "david bowie";
$db->collection->aggregate(
array(
array( '$project' => array( 'Likes' => '$music.likes' ) ),
array( '$match' => array( 'Likes.name' => $artist ) ),
array( '$sort' => array( 'Likes.strength' => 1 ) ),
array( '$limit' => 10 )
)
);
the match does works, but it only sort the Likes not the overall results. also - is there a way not to return all the items in the Likes document but just the one that is related to the match?
here is the results I'm getting
[
{
["_id"]=> object(MongoId)#310 (1) { ["$id"]=> string(24) "507f1f77bcf86cd799439011",
["Likes"] => array(49) {
[0]=> array(2) { ["name"]=> string(11) "john lennon" ["strength"]=> float(100) },
[1]=> array(2) { ["name"]=> string(11) "david bowie" ["strength"]=> float(50) },
[2]=> array(2) { ["name"]=> string(11) "bob marley" ["strength"]=> float(20) },
...
}
},
{
["_id"]=> object(MongoId)#310 (1) { ["$id"]=> string(24) "54304264e77cc5a1670cb318",
["Likes"] => array(49) {
[0]=> array(2) { ["name"]=> string(11) "bob marley" ["strength"]=> float(100) },
[1]=> array(2) { ["name"]=> string(11) "john lennon" ["strength"]=> float(70) },
[2]=> array(2) { ["name"]=> string(11) "david bowie" ["strength"]=> float(60) },
...
}
}
]
should I be using a different combination of commands in the aggregate?