简体   繁体   中英

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).

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

Currently my Preference Schema is set up as an object with 8 different fields, boolean for true/ false. I've tried doing that as an array where if the preference is checked, then append to the preference schema array. 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. 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:

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

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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