aggregation framework - MongoDB Sorting by relevance by matching sub documents -
i have document must searched according value in subdocument , sorted relevancy.
while researching topic, came across question. know have use aggregation framework, solution didn't cover subdocuments.
for example purposes wanted grab every document had sub documents teams.name ['blue', 'red', 'green'] , sorted based on matches 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 be:
item total matches -------- -------------- henderson 3 wilkins 2 sandy 1
how achieve this?
you can try 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 match documents team subdocuments matching @ least 1 of red, blue , green. second match remove spurious subdocuments included in first match.
Comments
Post a Comment