繁体   English   中英

如何在 Mongoose/MongoDB 中将按最多匹配数排序的结果返回到最少?

[英]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.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM