Sort by Releveance

The following often helps more that explications.

To bad you went the explications route. For example, is the field industry an array or a single value? Is the rindustry variable, an array or a single value?

Check Run aggregation pipeline and sort results by a set of match priorities - #3 by steevej

The idea is to use $addFields/$set stage to set sort values for your relevance.

You will start with a $match stage like:

match = { "$match" : {
    "isVerified" : true
} }

The second stage sets the relevance values.

relevance = { "$set" : {
  "_tmp" : {
    "industry" : { "$cond" : [
      { "$in" : { "$industry" , rindustry } } , 0 , 1
    ] } ,
    "country" : { "$cond" : [
      { "$eq" : { "$location.country" , rcountry } } , 0 , 1
    ] }
  }
} }

The you will $sort using the relevance value and your other sort criteria.

sort = { "$sort" : {
  "_tmp.industry" : 1 ,
  "_tmp.country" : 1 ,
  "salary" : -1
} }

The a little cosmetic $unset to remove the _tmp fields.

unset = { "$unset" : "_tmp" }

The whole pipeline being:

pipeline = [ match , set , sort , unset ]

Please read Formatting code and log snippets in posts before posting new code or sample documents. It helps when we can just cut-n-paste your field names and/or your code.

Your $facet matches seem to be mutually exclusive so I wonder how you can have duplicates.

Since isVerified $match is the same in all facets, it should be move into its own $match before the $facet.

1 Like