Mongo Sort by Count of Matches in Array

Viewed 1812

Lets say my test data is

db.multiArr.insert({"ID" : "fruit1","Keys" : ["apple", "orange", "banana"]})
db.multiArr.insert({"ID" : "fruit2","Keys" : ["apple", "carrot", "banana"]})

to get individual fruit like carrot i do

db.multiArr.find({'Keys':{$in:['carrot']}})

when i do an or query for orange and banana, i see both the records fruit1 and then fruit2

db.multiArr.find({ $or: [{'Keys':{$in:['carrot']}}, {'Keys':{$in:['banana']}}]})

Result of the output should be fruit2 and then fruit1, because fruit2 has both carrot and banana

1 Answers
Related