問題描述
搜索條件的mongodb map reduce (mongodb map reduce for search criteria)
我有一個包含名為 searchTerms 的字段的 mongo 文檔。這是一個包含單詞的數組 例如 ["term1","term2", "term3","term4"]
我想編寫一個按相關性返回文檔的函數。這意味著在 searchCriteria 中搜索詞最多的文檔首先緊隨其後,其次是數量最多的詞等。
示例:
文檔:
{"_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搜索條件:["a","b","c"] 結果應該是:
{"_id":"1", "searchTerms":["a","b","c","d"]}
{"_id":"2", "searchTerms":["a","b","x","q"]}
{"_id":"3", "searchTerms":["a","e","x","n"]}
我已經編寫了一個函數來執行此操作,但是它非常複雜並且我認為效率低下。我正在閱讀有關 map reduce 的內容,並想知道它在這種情況下是否有幫助?我絞盡腦汁想辦法解決這個問題。我不確定它是否可以?如果是,有人可以告訴我它是如何工作的嗎?
參考解法
方法 1:
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
}
}])