modify-score

For the complete MongoDB documentation index, see www.mongodb.com/docs/llms.txt

<!-- Tab options on this page. Append to the .md URL to filter: ?tabs=<id,...> select specific tabs (e.g. ?tabs=nodejs,shell) ?allTabs=true include every tab (no param) default: one tab per tabset

Available tabs: other tabs: number, patheg, arithmetic, constant, gauss, path, score, unary -->

Modify the Score

The following score modifying options are available to all operators. For details and examples, click any of the following options:

  • [boost](https://www.mongodb.com/docs/search/query/score/modify-score.md#std-label-scoring-boost

  • [constant](https://www.mongodb.com/docs/search/query/score/modify-score.md#std-label-scoring-constant

  • [embedded](https://www.mongodb.com/docs/search/query/score/modify-score.md#std-label-scoring-embedded

  • [function](https://www.mongodb.com/docs/search/query/score/modify-score.md#std-label-scoring-function

boost

The boost option multiplies a result's base score by a given number or the value of a numeric field in the documents. For example, you can use boost to increase the importance of certain matching documents in the result.

Note:

  • You can't use the boost and constant options together.

  • The boost option with path is the same as multiplying using the [function](https://www.mongodb.com/docs/search/query/score/modify-score.md#std-label-scoring-function option with a [path expression.](https://www.mongodb.com/docs/search/query/score/modify-score.md#std-label-function-score-expression

Fields

The boost option takes the following fields:

Field Type Necessity Description
value float Conditional Number to multiply the default base score by. Value must be a positive number. Either value or path is required, but you can't specify both.
path string Conditional Name of the numeric field whose value to multiply the default base score by. Either path or value is required, but you can't specify both.
undefined float Optional Numeric value to substitute for path if the numeric field specified through path is not found in the documents. If omitted, defaults to 0. You can specify this only if you specify path.

Examples

The following examples use the movies collection in the sample_mflix database. If you have the [sample dataset](https://www.mongodb.com/docs/manual/sample-data.md#std-label-available-sample-datasets on your cluster, you can create the MongoDB Search default index and run the example queries on your cluster.

The sample [compound](https://www.mongodb.com/docs/search/query/operators-collectors/compound.md#std-label-compound-ref queries demonstrate how to increase the importance of one search criteria over another. The queries include a $project stage to exclude all fields except title and score.

Tab

In the following example, the [compound](https://www.mongodb.com/docs/search/query/operators-collectors/compound.md#std-label-compound-ref operator uses [text](https://www.mongodb.com/docs/search/query/operators-collectors/text.md#std-label-text-ref operator to search for the term Helsinki in the plot and title fields. The query for the title field uses score with the boost option to multiply the score results by 3, as specified in the value field.

db.movies.aggregate([
  {
    "$search": {
      "compound": {
        "should": [{
          "text": {
            "query": "Helsinki",
            "path": "plot"
          }
        },
        {
          "text": {
            "query": "Helsinki",
            "path": "title",
            "score": { "boost": { "value": 3 } }
          }
        }]
      }
    }
  },
  {
    "$limit": 5
  },
  {
    "$project": {
      "_id": 0,
      "title": 1,
      "plot": 1,
      "score": { "$meta": "searchScore" }
    }
  }
])

This query returns the following results, in which the score for documents where the title matches the query term is multiplied by 3 from its base value:

[
  {
    plot: 'Epic tale about two generations of men in a wealthy Finnish family, spanning from the 1960s all the way through the early 1990s. The father has achieved his position as director of the ...',
    title: 'Kites Over Helsinki',
    score: 12.2470121383667
  },
  {
    plot: 'Alex is Finlander married to an Italian who works as a taxi driver in Berlin. One night in his taxi come two men with a briefcase full of money. Unluckily for Alex, they are being chased by...',
    title: 'Helsinki-Naples All Night Long',
    score: 9.56808090209961
  },
  {
    plot: 'The recession hits a couple in Helsinki.',
    title: 'Drifting Clouds',
    score: 4.5660295486450195
  },
  {
    plot: 'Two teenagers from Helsinki are sent on a mission by their drug dealer.',
    title: 'Sairaan kaunis maailma',
    score: 4.041563034057617
  },
  {
    plot: 'A murderer tries to leave his criminal past in East Helsinki and make a new life for his family',
    title: 'Bad Luck Love',
    score: 3.6251673698425293
  }
]

constant

The constant option replaces the base score with a specified number.

Note:

You must not use the constant and boost options together.

Examples

The following example uses the default index on the sample_mflix.movies collection to query the plot and title fields using the [compound](https://www.mongodb.com/docs/search/query/operators-collectors/compound.md#std-label-compound-ref operator. In the query, the [text](https://www.mongodb.com/docs/search/query/operators-collectors/text.md#std-label-text-ref operator uses score with the constant option to replace all score results with 5 for results that match the query against the title field only.

db.movies.aggregate([
  {
    "$search": {
      "compound": {
        "should": [{
          "text": {
            "query": "tower",
            "path": "plot"
          }
        },
        {
          "text": {
            "query": "tower",
            "path": "title",
            "score": { "constant": { "value": 5 } }
          }
        }]
      }
    }
  },
  {
    "$limit": 5
  },
  {
    "$project": {
      "_id": 0,
      "title": 1,
      "plot": 1,
      "score": { "$meta": "searchScore" }
    }
  }
])

The above query returns the following results, in which the score for documents that match the query against the title field only is replaced with the specified constant value:

[
  {
    plot: 'Several months after witnessing a murder, residents of Tower Block 31 find themselves being picked off by a sniper, pitting those lucky enough to be alive into a battle for survival.',
    title: 'Tower Block',
    score: 8.15460205078125
  },
  {
    plot: "When a group of hard-working guys find out they've fallen victim to their wealthy employer's Ponzi scheme, they conspire to rob his high-rise residence.",
    title: 'Tower Heist',
    score: 5
  },
  {
    plot: 'Toru Kojima and his friend Koji are young student boys with one thing in common - they both love to date older women. Koji is a playboy with several women, young and older, whereas Toru is a romantic with his heart set on on certain lady.',
    title: 'Tokyo Tower',
    score: 5
  },
  {
    plot: 'A middle-aged mental patient suffering from a split personality travels to Italy where his two personalities set off all kinds of confusing developments.',
    title: 'The Leaning Tower',
    score: 5
  },
  {
    plot: 'A documentary that questions the cost -- and value -- of higher education in the United States.',
    title: 'Ivory Tower',
    score: 5
  }
]

embedded

Note:

You can use this option with the [embeddedDocument](https://www.mongodb.com/docs/search/query/operators-collectors/embedded-document.md#std-label-embedded-document-ref operator only.

The embedded option allows you to configure how to:

  • Aggregate the scores of multiple matching embedded documents.

  • Modify the score of an [embeddedDocument](https://www.mongodb.com/docs/search/query/operators-collectors/embedded-document.md#std-label-embedded-document-ref operator after aggregating the scores from matching embedded documents.

Fields

The embedded option takes the following fields:

Field Type Necessity Description
aggregate string Optional Configures how to combine scores of matching embedded documents. Value must be one of the following aggregation strategies: sum - (Default) Sum the score of all matching embedded documents.; maximum - Choose the greatest score of all matching embedded documents.; minimum - Choose the least high score of all matching embedded documents.; mean - Choose the average (arithmetic mean) score of all matching embedded documents. MongoDB Search includes scores of matching embedded documents only when computing the average. MongoDB Search doesn't count embedded documents that don't satisfy query predicates as documents with scores of zero. If omitted, this field defaults to sum.
outerScore [Scoring Option](https://www.mongodb.com/docs/search/query/score/modify-score.md#std-label-scoring-options Optional Specifies the score modification to apply after applying the aggregation strategy.

Examples

The following sample query uses an index named default on the sample_analytics.transactions collection. The index configures an embeddedDocuments type on documents in the transactions array and string type for transactions.symbol and transactions.transaction_code fields.

Example:

{
  "mappings": {
    "dynamic": true,
    "fields": {
     "transactions": {
        "dynamic": true,
        "fields": {
          "symbol": {
            "type": "string"
          },
          "transaction_code": {
            "type": "string"
          }
        },
        "type": "embeddedDocuments"
      }
    }
  }
}

The sample query on the transactions field, which contains an array of documents, includes a $limit stage to limit the output to 10 results and a $project stage to:

  • Exclude all fields except account_id and transaction_count.

  • Add a field named score that applies an aggregation strategy and further score modification.

Note:

You can use function.

The query searches for accounts that have bought AMD and multiplies the largest single AMD purchase (by number of shares) by the log1p value of the number of transactions that the account has made in this period. It ranks the accounts based on the following:

  • Number of AMD bought in a single transaction

  • Number of transactions in the last period

db.transactions.aggregate({
  "$search": {
    "embeddedDocument": {
      "path": "transactions",
      "operator": {
        "compound": {
          "must": [
            {
              "text": {
                "path": "transactions.symbol",
                "query": "amd"
              }
            },
            {
              "text": {
                "path": "transactions.transaction_code",
                "query": "buy"
              }
            }
          ],
          "score": {
            "function": {
              "path": {
                "value": "transactions.amount",
                "undefined": 1.0
              }
            }
          }
        }
      },
      "score": {
        "embedded": {
          "aggregate": "maximum",
          "outerScore": {
            "function": {
              "multiply": [
                {
                  "log1p": {
                    "path": {
                      "value": "transaction_count"
                    }
                  }
                },
                {
                  "score": "relevance"
                }
              ]
            }
          }
        }
      }
    }
  }
},
{ "$limit": 10 },
{
  "$project": {
    "_id": 0,
    "account_id": 1,
    "transaction_count": 1,
    "score": { $meta: "searchScore" }
  }
})

MongoDB Search ranks accounts that have made many transactions in the last period and bought many AMD in a single transaction highly.

[
  { account_id: 467651, transaction_count: 99, score: 19982 },
  { account_id: 271554, transaction_count: 96, score: 19851.822265625 },
  { account_id: 71148, transaction_count: 99, score: 19840 },
  { account_id: 408143, transaction_count: 100, score: 19836.76953125 },
  { account_id: 977774, transaction_count: 98, score: 19822.64453125 },
  { account_id: 187107, transaction_count: 96, score: 19754.470703125 },
  { account_id: 492843, transaction_count: 97, score: 19744.998046875 },
  { account_id: 373169, transaction_count: 93, score: 19553.697265625 },
  { account_id: 249078, transaction_count: 89, score: 19436.896484375 },
  { account_id: 77690, transaction_count: 90, score: 19418.017578125 }
]

function

The function option allows you to alter the final score of the document using a numeric field . You can specify the numeric field for computing the final score through an [expression](https://www.mongodb.com/docs/search/query/score/modify-score.md#std-label-function-score-expression. If the final result of the function score is less than 0, MongoDB Search replaces the score with 0.

Note:

You can use function inside the score option of the embeddedDocument.

Expressions

Use the following expressions with the function option to alter the final score of the document:

  • Arithmetic expressions, which add or multiply a series of numbers.

  • Constant expressions, which allow a [constant](https://www.mongodb.com/docs/search/query/score/modify-score.md#std-label-scoring-constant number in the function score.

  • Gaussian decay expressions, which decay, or reduces, the scores by multiplying at a specified rate.

  • Path expressions, which incorporate an indexed numeric field value into a function score.

  • Score expressions, which return the relevance score assigned by MongoDB Search.

  • Unary expressions, which are expressions that take a single argument. In MongoDB Search, you can calculate the log10(x) or log10(x+1) of a specified number.

Note:

MongoDB Search function scores are always float values and precision might be lost for very large or small numbers.

Arithmetic

An arithmetic expression adds or multiplies a series of numbers. For example, you can use arithmetic expression to modify relevance ranking through a numeric field from a data enrichment pipeline. It must include one of the following options:

Option Type Description
add array of [expressions](https://www.mongodb.com/docs/search/query/score/modify-score.md#std-label-function-score-expression Adds a series of numbers. Takes an array of [expressions](https://www.mongodb.com/docs/search/query/score/modify-score.md#std-label-function-score-expression, which can have negative values. Array length must be greater than or equal to 2. For example: `“function”: {
“add”: [
{“path”: “rating”},
{“score”: “relevance”}
]
}In the previous example, MongoDB Search uses thepathandscoreexpressions to add the following: Numeric value of theratingfield or0, if therating` field is not present in the document; Relevance score, which is the score MongoDB Search assigns based on relevance
multiply array of [expressions](https://www.mongodb.com/docs/search/query/score/modify-score.md#std-label-function-score-expression Multiplies a series of numbers. Takes an array of [expressions](https://www.mongodb.com/docs/search/query/score/modify-score.md#std-label-function-score-expression, which can have negative values. Array length must be greater than or equal to 2. For example: `“function”: {
“multiply”: [
{
“path”: {
“value”: “popularity”,
“undefined”: 2.5
}
},
{
“score”: “relevance”
},
{
“constant”: 0.75
}
]
}In the previous example, MongoDB Search uses thepath,score, andconstantexpressions to alter the final score of the document. It multiplies the following: Numeric value of the path expression, which is the numeric value of thepopularityfield or2.5, if thepopularityfield is not present in the document; Relevance score, which is the score MongoDB Search assigns based on relevance; Constant value of0.75`

Note:

You can't replace an arithmetic expression that evaluates to undefined with a constant value.

Examples

The following examples use the default index on the sample_mflix.movies collection to query the title field. The sample queries include a $limit stage to limit the output to 5 results and a $project stage to exclude all fields except title and score.

Arithmetic

Example:

In this example, the [text](https://www.mongodb.com/docs/search/query/operators-collectors/text.md#std-label-text-ref operator uses score with the function option to multiply the following:

  • Numeric value of the path expression, which is the value of the imdb.rating field in the documents or 2, if the imdb.rating field is not in the document

  • Relevance score, or the current score of the document

db.movies.aggregate([{
  "$search": {
    "text": {
      "path": "title",
      "query": "men",
      "score": {
        "function":{
          "multiply":[
            {
              "path": {
                "value": "imdb.rating",
                "undefined": 2
              }
            },
            {
              "score": "relevance"
            }
          ]
        }
      }
    }
  }
},
{
  $limit: 5
},
{
  $project: {
    "_id": 0,
    "title": 1,
    "score": { "$meta": "searchScore" }
  }
}])

This query returns the following results, in which the score is replaced with the specified function value:

{ "title" : "Men...", "score" : 23.431293487548828 }
{ "title" : "12 Angry Men", "score" : 22.080968856811523 }
{ "title" : "X-Men", "score" : 21.34803581237793 }
{ "title" : "X-Men", "score" : 21.34803581237793 }
{ "title" : "Matchstick Men", "score" : 21.05954933166504 }