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

Javascript 在Mongoose/MongoDB中,如何将按最多匹配数排序的结果返回到最少匹配数?,javascript,node.js,angular,mongodb,angular8,Javascript,Node.js,Angular,Mongodb,Angular8,我正在MEAN stack(angular、node.js、mongodb、express)中创建一个应用程序,用户在其中填写一个包含8个选项的首选项表单,我希望能够查询数据库,并找到按最密切相关的首选项选项排序、最不密切相关的用户(至少1个匹配项) 我查过弹性搜索,但我认为这只是一个基于索引的搜索,实际上不会完全返回用户列表。我有哪些选择?我应该切换到其他数据库吗?我在mongoose中查找的基于匹配的查询没有那么动态 目前,我的首选项模式被设置为具有8个不同字段的对象,布尔值表示真/假。我曾

我正在MEAN stack(angular、node.js、mongodb、express)中创建一个应用程序,用户在其中填写一个包含8个选项的首选项表单,我希望能够查询数据库,并找到按最密切相关的首选项选项排序、最不密切相关的用户(至少1个匹配项)

我查过弹性搜索,但我认为这只是一个基于索引的搜索,实际上不会完全返回用户列表。我有哪些选择?我应该切换到其他数据库吗?我在mongoose中查找的基于匹配的查询没有那么动态

目前,我的首选项模式被设置为具有8个不同字段的对象,布尔值表示真/假。我曾尝试将其作为一个数组,如果选中了首选项,则将其附加到首选项模式数组中。到目前为止,我还没有找到任何固溶体

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
}

事实上,我把这个项目搁置了两个月,因为我和我在编码训练营的同伴们无法找到解决方案。我最终只能满足于找到所有符合性别偏好的东西。请让我知道我应该朝哪个方向看。

您可以使用聚合功能,其中一些类似于:

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
  }
}

感谢您的输入,如果查询输入(相当于将用户自己的首选项与其他用户进行比较)非常动态,这会起作用吗?从这里我可以看到,您是否为每个匹配分配了一个权重值,然后返回最匹配的用户列表?等我到家后,我会设法修补一下