How to calculate score for query of $and $or document?

Hi Everyone,

I have query like:

{ $and: [{“status”: “published”},{“enableLocale.en”: true},{“modelSlug”:{$ne: “abc_abc”} }, {“enableListing.en”: true}, {$or: [ { “countryTagsName.en”: “Pakistan” }, {“agencyTagsName.en”: “Abcde”}, {“agencyTagsName.en”: “Abcdef”}, {“focusTagsName.en”: “Education”}, {“tagsName.en”: “|Abcdefg”}]}]}

how can we calculate score for documents that match the query?

Please read Formatting code and log snippets in posts and update your query.

Please provide sample documents.

Please define by what you mean by

2 Likes

Ok @steevej
let say I’m running this simple query in my dataset

and it work fine but I want to show those document on top which match both $OR condition and those which match one condition show on last so for that I want to add score to each document if it match both condition then add score = 2 and if match one condition then score = 1 and then i’ll sort it with score.

but problem is how to calculate score for each document ?

I want my query to return this type of document like:

[
  {
    "countryTagsName":{
      "en": "Pakistan"
    },
    "agencyTagsName": {
      "en": "Abcde"
    },
    "score": 2
  },
  {
    "countryTagsName":{
      "en": "Pakistan"
    },
    "agencyTagsName": {
      "en": "Ab"
    },
    "score": 1
  }
]

I read this https://www.mongodb.com/docs/atlas/atlas-search/scoring/
link suggest to create index but I have very long query of $or which match 9 to 10 fields and creating such large compound index is I thing not good so that I don’t wanna create index for that.

I have one other solution to get record from query and add score and sort it from JavaScript code but I want to do that from query.

can you please help me out from this.

Thank you in advance.

Atlas search and queries like you shared are 2 different things.

The only way I can see how you may achieve that with aggregation is to

  1. $match with your $or
  2. add an $addFields that would $sum 1 for each $or using $cond to create the score
  3. then $sort using the score
2 Likes

@steevej can you please explain or write query for how to use $addFields and $sum $or $cond together for my case ?

What have you tried so far?

Did you look at the many examples in the documentation for $addFields, $sum, $or and $cond.

match_1 = { "countryTagsName.en" : "Pakistan" }
...
match_N = { "focusTagsName.en" , "Education" }
match = { $match : { $or : [ match_1 , match_2 , ... , match_N ] } }
score = { $sum : [ { $cond : {match_1,1,0} , { $cond : {match_2,1,0}} , ... , { $cond : {match_N,1,0}} ] }
addFields = { $addFields : score }
sort = { $sort : { score : -1 } }
pipeline = [ match , addFields , sort ]
2 Likes

A post was split to a new topic: Atlas Search - scoring