Reputation: 1452
I have mongo documents that contain a field called searchTerms. This is an array with words in it E.g. ["term1","term2", "term3","term4"]
I want to write a function that returns documents by relevance. That means that the documents with the most search terms within the searchCriteria are first followed the next highest amount terms etc.
Example:
Documents:
{"_id":"1", "searchTerms":["a","b","c","d"]}
{"_id":"2", "searchTerms":["a","b","x","q"]}
{"_id":"3", "searchTerms":["a","e","x","n"]}
{"_id":"4", "searchTerms":["e","f","g","z"]}
For search terms: ["a","b","c"] the result should be:
{"_id":"1", "searchTerms":["a","b","c","d"]}
{"_id":"2", "searchTerms":["a","b","x","q"]}
{"_id":"3", "searchTerms":["a","e","x","n"]}
I have written a function to do this however it's very complicated and i think inefficient. I was reading about map reduce and wondering if it can help in this situation? I have racked my brain try to work out how this could be done. I'm not sure if it can or can't be? If yes can someone please tell me how it would work?
Upvotes: 0
Views: 96
Reputation: 75984
A simple set operator will suffice. Use $setIntersection for comparsion with input array and $project $size of intersected array. $sort on size descending and project the final response.
aggregate([{
"$project": {
"_id":0,
"fields" : "$$ROOT",
"matches": {
"$size": {
"$setIntersection": [
"$searchTerms", ["a", "b"]
]
}
}
}
}, {
"$sort": {
"matches": -1
}
}])
Upvotes: 1