简体   繁体   English

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

[英]How to return results ordered by most number of matches to least in Mongoose/MongoDB?

I'm creating an application in MEAN stack (angular, node.js, mongodb, express) where users fill out a preference form that includes 8 options, I want to be able to query the database and find users ordered by closest related preference options to the least close related (min 1 match).我正在 MEAN 堆栈(角度、node.js、mongodb、express)中创建一个应用程序,其中用户填写包含 8 个选项的首选项表格,我希望能够查询数据库并找到按最接近的相关首选项排序的用户最不密切相关(最少 1 场比赛)。

I've looked up Elastic Search but I think that's just an index based search and wouldn't actually return a list of users completely.我查找了 Elastic Search,但我认为这只是一个基于索引的搜索,实际上并不会完全返回用户列表。 What are some of my options?我有哪些选择? Should I switch to a different database?我应该切换到不同的数据库吗? The match based queries I've looked up for mongoose is not as dynamic...我为 mongoose 查找的基于匹配的查询不是动态的......

Currently my Preference Schema is set up as an object with 8 different fields, boolean for true/ false.目前,我的 Preference Schema 设置为具有 8 个不同字段的 object,boolean 为真/假。 I've tried doing that as an array where if the preference is checked, then append to the preference schema array.我已经尝试将其作为一个数组来执行,如果选中了首选项,则将 append 设置为首选项架构数组。 So far I'm not able to come up with any solid solutions.到目前为止,我无法提出任何可靠的解决方案。

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}

}) })

That's inside the User Schema:这在用户模式中:

UserSchema = //some code here{
 preference: {
      type: PreferenceSchema,
      default: null
    }

// the rest of the schema
}

I actually put this project away for 2 months because I and my cohort- mates at the coding boot camp couldn't figure out a solution for it.实际上,我把这个项目搁置了 2 个月,因为我和我在编码训练营的同伴们无法找到解决方案。 I ended up just settling for find all that match the gender preference.我最终只是满足于找到所有符合性别偏好的东西。 Please let me know what direction I should be looking into.请让我知道我应该研究的方向。

You can use aggregation function, some like this:您可以使用聚合 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