I have a document that must be searched according to a value in its subdocument and sorted by relevancy.
While researching this topic, I came across this question. I now know I have to use the aggregation framework, but the solution didn't cover subdocuments.
For example purposes say the I wanted to grab every document that had sub documents with the teams.name ['blue', 'red', 'green'] and sorted based on the most matches it had.
League Collection:
{
coach: Henderson,
teams:
[
{
name: red,
logo: bird,
division: east
},
{
name: blue,
logo: bluejay,
division: west
},
{
name: green,
logo: monkey,
division: east
}
]
}
{
coach: Wilkins,
teams:
[
{
name: red,
logo: bird,
division: east
},
{
name: blue,
logo: bluejay,
division: west
},
]
}
{
coach: Sandy,
teams:
[
{
name: red,
logo: bird,
division: east
}
]
}
The end result would be:
item total matches
-------- --------------
Henderson 3
Wilkins 2
Sandy 1
How would I achieve this?
You can try the following:
db.league.aggregate(
{$match:{'teams.name':{$in:['red','blue','green']}}},
{$unwind:'$teams'},
{$match:{'teams.name':{$in:['red','blue','green']}}},
{$project:{'item':'$coach','teams':1}},
{$group:{_id:'$item',total:{$sum:1}}},
{$sort:{total:-1}}
)
The first match will match for all documents with team subdocuments matching at least one of red, blue and green. The second match will remove spurious subdocuments that were included in the first match.