[英]How to return results ordered by most number of matches to least in Mongoose/MongoDB?
我正在 MEAN 堆棧(角度、node.js、mongodb、express)中創建一個應用程序,其中用戶填寫包含 8 個選項的首選項表格,我希望能夠查詢數據庫並找到按最接近的相關首選項排序的用戶最不密切相關(最少 1 場比賽)。
我查找了 Elastic Search,但我認為這只是一個基於索引的搜索,實際上並不會完全返回用戶列表。 我有哪些選擇? 我應該切換到不同的數據庫嗎? 我為 mongoose 查找的基於匹配的查詢不是動態的......
目前,我的 Preference Schema 設置為具有 8 個不同字段的 object,boolean 為真/假。 我已經嘗試將其作為一個數組來執行,如果選中了首選項,則將 append 設置為首選項架構數組。 到目前為止,我無法提出任何可靠的解決方案。
My Schema:
const PreferenceSchema = new mongoose.Schema({
gender: {type: String, required: [true, 'Please select a gender preference.']},
weight_loss: {type: Boolean, default: false},
cardio: {type: Boolean, default: false},
endurance: {type: Boolean, default: false},
flexibility: {type: Boolean, default: false},
strength: {type: Boolean, default: false},
muscle: {type: Boolean, default: false},
genFit: {type: Boolean, default: false}
})
這在用戶模式中:
UserSchema = //some code here{
preference: {
type: PreferenceSchema,
default: null
}
// the rest of the schema
}
實際上,我把這個項目擱置了 2 個月,因為我和我在編碼訓練營的同伴們無法找到解決方案。 我最終只是滿足於找到所有符合性別偏好的東西。 請讓我知道我應該研究的方向。
您可以使用聚合 function,有些像這樣:
PreferenceSchema.aggregation([{
$search: ...
}, {
$addFields: {
gender_value: {$cond: [{$eq: ['$genger', gender]}, 1, 0]}
weight_loss_value: {$cond: [{$eq: ['$weight_loss', weightLoss]}, 1, 0]}
...
}
}, {
$project: {
match: {$sum: ['$gender_value', '$weight_loss_value', ...]}
}
}, {
$sort: {
match: 1
}
}
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.