meteor - MongoDB: find documents that match the most tags -


in meteor app, have huge collection of documents, each field tags, this:

{..., tags: ["a","b","c"], ...}, {..., tags: ["a","b","d"], ...}, {..., tags: ["b","c","e"], ...}, {..., tags: ["x","y","z"], ...}, .... 

now want query collection on server tags, eg: ["a","d","y"] , results match @ least 1 tag, , resultset sorted number of matching tags. so, in exampleset result should be:

{..., tags: ["a","b","d"], ...}, {..., tags: ["a","b","c"], ...}, {..., tags: ["x","y","z"], ...} 

because first doc has 2 matches, "a" , "d", , other 2 elements have 1 match, "a" , "y".

currently know can use $in match documents have @ least 1 match, $all documents every tag matches, doesn't cut somehow. use mongodb's aggregate framework if needed.

what needed query like?

i use mongodb's aggregate framework if needed.

you need use the aggregation pipeline, can written below:

  • match documents having @ least 1 matching value in tags array.
  • we unwinding , working on tags array, keep copy of tags array in each record.
  • unwind tags array.
  • match records have tags value present in input array.
  • group _id field , calculate number of documents have matched.
  • sort groups based on number of matches.
  • project required fields along original tags array copy had created.

code:

var inp = ["a","d","y"];  db.collection.aggregate([ {$match:{"tags":{$in:inp}}}, {$project:{"tagscopy":"$tags","tags":1}}, {$unwind:"$tags"}, {$match:{tags:{$in:inp}}}, {$group:{"_id":"$_id","noofmatches":{$sum:1},"tags":{$first:"$tagscopy"}}}, {$sort:{noofmatches:-1}}, {$project:{"_id":0,"noofmatches":1,tags:1}} //remove noofmatches ,                                              //add other required                                              //fields necessary. ]) 

o/p:

{ "noofmatches" : 2, "tags" : [ "a", "b", "d" ] } { "noofmatches" : 1, "tags" : [ "x", "y", "z" ] } { "noofmatches" : 1, "tags" : [ "a", "b", "c" ] } 

Comments

Popular posts from this blog

python - mat is not a numerical tuple : openCV error -

c# - MSAA finds controls UI Automation doesn't -

wordpress - .htaccess: RewriteRule: bad flag delimiters -