customize-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: fts-vs, data-explorer, constant, boostsingle, boostmulti, fuction-score, simple, multi, bury-genre, bury-id, Basic, arithmetic, gauss, path, unary -->
Customize the Score of the Documents in the Results
You can customize the [score](https://www.mongodb.com/docs/search/query/score/overview.md#std-label-scoring-ref of the documents in the results. By adjusting how scores are calculated, you can ensure that the most pertinent documents are ranked higher in the search results. To learn more about the different ways in which you can customize the score, see [Score the Documents in the Results](https://www.mongodb.com/docs/search/query/score/overview.md#std-label-scoring-ref. This page demonstrates how to:
-
Modify the score of the documents in the results to boost or bury the results.
-
Normalize your [
$search](https://www.mongodb.com/docs/search/query/aggregation-stages/search.md#mongodb-pipeline-pipe.-search query score in the range from0to1in the subsequent stages of your aggregation pipeline.
Modify the Score of the Documents in the Results
A MongoDB Search query assigns every returned document a score based on its relevance. The documents included in a result set return in order from highest to lowest score. To learn more, see [Score the Documents in the Results.](https://www.mongodb.com/docs/search/query/score/overview.md#std-label-scoring-ref
You can use the following options with all operators to modify the default scoring behavior. 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
This section demonstrates how to add weights to your search fields to boost or bury the documents in the results or a category of results. Specifically, it demonstrates how to assign one or more values to a field to return results with an increased or decreased score.
Example Index
You can set up an index with [dynamic mappings](https://www.mongodb.com/docs/search/indexes/define-field-mappings.md#std-label-static-dynamic-mappings enabled to index all the fields in the collection. Alternatively, use static mappings on the fields that you want to query and sort the results by. To learn more about creating MongoDB Search indexes, see [Manage MongoDB Search Indexes.](https://www.mongodb.com/docs/search/indexes/manage-indexes.md#std-label-ref-create-index
Example Queries
The sample queries demonstrate how to boost or bury the documents in the results. They use the [compound operator](https://www.mongodb.com/docs/search/query/operators-collectors/compound.md#std-label-compound-ref to combine two or more operators into a single query.
Boost the Results
Use the compound operator to combine two or more operators into a single query. Use score options to alter the relevance score that MongoDB Search returns.
Use the title and year fields in the sample_mflix.movies namespace to boost the relevance score that MongoDB Search returns for movie titles that contain the term snow. If you set up the index on the movies collection, you can run the following queries.
- In Atlas, go to the Search & Vector Search page for your cluster.
You can go the MongoDB Search page from the Search & Vector Search option, or the Data Explorer.
### Search & Vector Search
If it's not already displayed, select the organization that contains your project from the Organizations menu in the navigation bar.
If it's not already displayed, select your project from the Projects menu in the navigation bar.
In the sidebar, click Search & Vector Search under the Database heading.
-
If you have no clusters, click Create cluster to create one. To learn more, see [Create an Atlas Infinite or Atlas Core Cluster.](https://www.mongodb.com/docs/atlas/tutorial/create-new-cluster.md#std-label-create-new-cluster
-
If your project has multiple clusters, select the cluster you want to use from the Select cluster dropdown, then click Go to Search.
The Search & Vector Search page displays.
- Go to the Search Tester.
Click the Query button to the right of the index to query.
- View and edit the query syntax.
Click Edit Query to view a default query syntax sample in JSON (Javascript Object Notation) format.
- Run the following MongoDB Search queries with the
compoundoperator on themoviescollection.
Copy and paste the following query into the Query Editor, and then click the Search button in the Query Editor.
The following examples use the compound operator with subqueries to search for movies between the years 2013 to 2015 with the term snow in the title field.
### Constant
The following query:
-
Uses the following
compoundoperator clauses:-
filterclause with the [range](https://www.mongodb.com/docs/search/query/operators-collectors/range.md#std-label-range-ref operator to search for movies between the years2013to2015. -
shouldclause with the [text](https://www.mongodb.com/docs/search/query/operators-collectors/text.md#std-label-text-ref operator to query for the termsnowin thetitlefield and alter thescorewith theconstantoption. Theconstantoption replaces all score results for the search term with5.
-
-
Specifies the [highlight](https://www.mongodb.com/docs/search/query/highlighting.md#std-label-highlight-ref option to return snippets of text from the
titlefield that match the query. The snippets contain matching text specified withtype: 'hit', and adjacent text specified withtype: 'text'.
json
[
{
$search: {
index: "default",
compound: {
filter: [{
range: {
path: "year",
gte: 2013,
lte: 2015
}
}],
should: [{
text: {
query: "snow",
path: "title",
score: {constant: {value: 5}}
}
}]
},
highlight:{
path: "title"
}
}
}
]
Output:
```text SCORE: 5 _id: "573a13d7f29313caabda38ad" Snow in Paradise Matching fields: title
SCORE: 5 _id: "573a13e2f29313caabdbeded" Dead Snow 2: red vs. Matching fields: title
SCORE: 5 _id: "573a13e6f29313caabdc66c4" The Snow White Murder Case Matching fields: title
SCORE: 5 _id: "573a13edf29313caabdd37bd" Snow on the Blades Matching fields: title
SCORE: 0 _id: "573a13acf29313caabd29366" No highlights found. Matching fields: unknown
SCORE: 0 _id: "573a13adf29313caabd2b765" No highlights found. Matching fields: unknown
SCORE: 0 _id: "573a13b0f29313caabd333e7" No highlights found. Matching fields: unknown
SCORE: 0 _id: "573a13b0f29313caabd3486a" No highlights found. Matching fields: unknown
SCORE: 0 _id: "573a13b1f29313caabd3719d" No highlights found. Matching fields: unknown
SCORE: 0 _id: "573a13b2f29313caabd3abb9" No highlights found. Matching fields: unknown ```
The first four documents in the results have a higher score because the should clause in the query specifies a preference for documents with snow in the title. The should clause also alters the score for the query term snow using the constant option.
- Expand your query results.
The Search Tester might not display all the fields in the documents it returns. To view all the fields, including the field that you specify in the query path, expand the document in the results.
1) Connect to your cluster in [mongosh](https://www.mongodb.com/docs/mongodb-shell.md#mongodb-binary-bin.mongosh.
Open [mongosh](https://www.mongodb.com/docs/mongodb-shell.md#mongodb-binary-bin.mongosh in a terminal window and connect to your cluster. For detailed instructions on connecting, see [Connect to a Cluster via mongosh.](https://www.mongodb.com/docs/atlas/mongo-shell-connection.md#std-label-connect-mongo-shell
2) Use the sample_mflix database.
Run the following command at [mongosh](https://www.mongodb.com/docs/mongodb-shell.md#mongodb-binary-bin.mongosh prompt:
javascript
use sample_mflix
3) Run the following MongoDB Search queries with the compound operator on the movies collection. The following examples use the compound operator with subqueries to search for movies between the years 2013 to 2015 with the term snow in the title field.
### Constant
This query uses the following pipeline stages:
-
[
$search](https://www.mongodb.com/docs/search/query/aggregation-stages/search.md#mongodb-pipeline-pipe.-search to query the collection. The query:-
Uses the following
compoundoperator clauses: -
filterclause with the [range](https://www.mongodb.com/docs/search/query/operators-collectors/range.md#std-label-range-ref operator to search for movies between the years2013to2015. -
shouldclause with the [text](https://www.mongodb.com/docs/search/query/operators-collectors/text.md#std-label-text-ref operator to query for the termsnowin thetitlefield and alter thescorewith theconstantoption. Theconstantoption replaces all score results for the search term with5. -
Specifies the [highlight](https://www.mongodb.com/docs/search/query/highlighting.md#std-label-highlight-ref option to return snippets of text from the
titlefield that match the query. The snippets contain matching text specified withtype: 'hit', and adjacent text specified withtype: 'text'.
-
-
[
$limit](https://www.mongodb.com/docs/manual/reference/operator/aggregation/limit.md#mongodb-pipeline-pipe.-limit stage to limit the output to10results. -
[
$project](https://www.mongodb.com/docs/manual/reference/operator/aggregation/project.md#mongodb-pipeline-pipe.-project stage to:-
Exclude all fields except
titleandyear -
Add a
scorefield
-
json
db.movies.aggregate([
{
"$search": {
"index": "default",
"compound": {
"filter": [{
"range": {
"path": "year",
"gte": 2013,
"lte": 2015
}
}],
"should": [{
"text": {
"query": "snow",
"path": "title",
"score": {"constant": {"value": 5}}
}
}]
},
"highlight": {
"path": "title"
}
}
},
{
"$limit": 10
},
{
"$project": {
"_id": 0,
"title": 1,
"year": 1,
"score": { "$meta": "searchScore" },
"highlights": { "$meta": "searchHighlights" }
}
}
])
MongoDB Search returns the following results for [constant:](https://www.mongodb.com/docs/search/query/score/modify-score.md#std-label-scoring-constant
json

[
{
title: 'Snow in Paradise',
year: 2014,
score: 5,
highlights: [
{
score: 1.382846713066101,
path: 'title',
texts: [
{ value: 'Snow', type: 'hit' },
{ value: ' in Paradise', type: 'text' }
]
}
]
},
{
title: 'Dead Snow 2: Red vs. Dead',
year: 2014,
score: 5,
highlights: [
{
score: 1.3924485445022583,
path: 'title',
texts: [
{ value: 'Dead ', type: 'text' },
{ value: 'Snow', type: 'hit' },
{ value: ' 2: Red vs. ', type: 'text' }
]
}
]
},
{
title: 'The Snow White Murder Case',
year: 2014,
score: 5,
highlights: [
{
score: 1.3525336980819702,
path: 'title',
texts: [
{ value: 'The ', type: 'text' },
{ value: 'Snow', type: 'hit' },
{ value: ' White Murder Case', type: 'text' }
]
}
]
},
{
title: 'Snow on the Blades',
year: 2014,
score: 5,
highlights: [
{
score: 1.3766303062438965,
path: 'title',
texts: [
{ value: 'Snow', type: 'hit' },
{ value: ' on the Blades', type: 'text' }
]
}
]
},
{ year: 2013, title: 'The Secret Life of Walter Mitty', score: 0, highlights: [] },
{ title: 'Jurassic World', year: 2015, score: 0, highlights: [] },
{ title: 'Action Jackson', year: 2014, score: 0, highlights: [] },
{ year: 2013, title: 'In Secret', score: 0, highlights: [] },
{ title: 'The Stanford Prison Experiment', year: 2015, score: 0, highlights: [] },
{ year: 2014, title: 'The Giver', score: 0, highlights: [] }
]
The first four documents in the results have a higher score because the should clause in the query specifies a preference for documents with snow in the title. The should clause also alters the score for the query term snow using the constant option.
- Connect to your cluster in MongoDB Compass.
Open MongoDB Compass and connect to your cluster. For detailed instructions on connecting, see [Connect to a Cluster via Compass.](https://www.mongodb.com/docs/atlas/compass-connection.md#std-label-atlas-connect-via-compass
- Use the
moviescollection in thesample_mflixdatabase.
On the Database screen, click the sample_mflix database, then click the movies collection.
-
Run a MongoDB Search compound query that alters the score using the [
constant](https://www.mongodb.com/docs/search/query/score/modify-score.md#std-label-scoring-constant option. The query performs the following tasks: -
Uses the following
compoundoperator clauses:-
filterclause with the [range](https://www.mongodb.com/docs/search/query/operators-collectors/range.md#std-label-range-ref operator to search for movies between the years2013to2015. -
shouldclause with the [text](https://www.mongodb.com/docs/search/query/operators-collectors/text.md#std-label-text-ref operator to query for the termsnowin thetitlefield and alter thescorewith theconstantoption. Theconstantoption replaces all score results for the search term with5.
-
-
Specifies the [highlight](https://www.mongodb.com/docs/search/query/highlighting.md#std-label-highlight-ref option to return snippets of text from the
titlefield that match the query. The snippets contain matching text specified withtype: 'hit', and adjacent text specified withtype: 'text'. -
Uses the following pipeline stages:
-
[
$limit](https://www.mongodb.com/docs/manual/reference/operator/aggregation/limit.md#mongodb-pipeline-pipe.-limit stage to limit the output to 10 results -
[
$project](https://www.mongodb.com/docs/manual/reference/operator/aggregation/project.md#mongodb-pipeline-pipe.-project stage to: -
Exclude all fields except
titleandyear -
Add two fields named
scoreandhighlights
-
To run this query in MongoDB Compass:
Click the Aggregations tab.
Click Select..., then configure each of the following pipeline stages by selecting the stage from the dropdown and adding the query for that stage. Click Add Stage to add additional stages.
| Pipeline Stage | Query |
|---|---|
$search |
`{ |
| “index”: “default”, | |
| “compound”: { | |
| “filter”: [{ | |
| “range”: { | |
| “path”: “year”, | |
| “gte”: 2013, | |
| “lte”: 2015 | |
| } | |
| }], | |
| “should”: [{ | |
| “text”: { | |
| “query”: “snow”, | |
| “path”: “title”, | |
| “score”: {“constant”: {“value”: 5}} | |
| } | |
| }] | |
| }, | |
| “highlight”: { “path”: “title” } | |
| }` | |
$limit |
10 |
$project |
`{ |
| “_id”: 0, | |
| “title”: 1, | |
| “year”: 1, | |
| “score”: { “$meta”: “searchScore” }, | |
| “highlights”: { “$meta”: “searchHighlights” } | |
| }` |
If you [enabled](https://www.mongodb.com/docs/compass/current/aggregation-pipeline-builder/#set-the-documents-limit-or-auto-preview-documents Auto Preview, MongoDB Compass displays the following documents next to the $project pipeline stage:
json
{
title: 'Snow in Paradise',
year: 2014,
score: 5,
highlights: [{
score: 1.382846713066101,
path: 'title',
texts: [
{ value: 'Snow', type: 'hit' },
{ value: ' in Paradise', type: 'text' }
]
}]
},
{
title: 'Dead Snow 2: Red vs. Dead',
year: 2014,
score: 5,
highlights: [{
score: 1.3924485445022583,
path: 'title',
texts: [
{ value: 'Dead ', type: 'text' },
{ value: 'Snow', type: 'hit' },
{ value: ' 2: Red vs. ', type: 'text' }
]
}]
},
{
title: 'The Snow White Murder Case',
year: 2014,
score: 5,
highlights: [{
score: 1.3525336980819702,
path: 'title',
texts: [
{ value: 'The ', type: 'text' },
{ value: 'Snow', type: 'hit' },
{ value: ' White Murder Case', type: 'text' }
]
}]
},
{
title: 'Snow on the Blades',
year: 2014,
score: 5,
highlights: [{
score: 1.3766303062438965,
path: 'title',
texts: [
{ value: 'Snow', type: 'hit' },
{ value: ' on the Blades', type: 'text' }
]
}]
},
{ year: 2013, title: 'The Secret Life of Walter Mitty', score: 0, highlights: [] },
{ title: 'Jurassic World', year: 2015, score: 0, highlights: [] },
{ title: 'Action Jackson', year: 2014, score: 0, highlights: [] },
{ year: 2013, title: 'In Secret', score: 0, highlights: [] },
{ title: 'The Stanford Prison Experiment', year: 2015, score: 0, highlights: [] },
{ year: 2014, title: 'The Giver', score: 0, highlights: [] }
The first four documents in the results have a higher score because the should clause in the query specifies a preference for documents with snow in the title. The should clause also alters the score for the query term snow using the constant option.
- Run MongoDB Search compound queries that alter the score using the [
boost](https://www.mongodb.com/docs/search/query/score/modify-score.md#std-label-scoring-boost option.
Click the Aggregations tab.
Click Select..., then configure each of the following pipeline stages by selecting the stage from the dropdown and adding the query for that stage. Click Add Stage to add additional stages.
### Simple Example
The query uses the following pipeline stages:
-
[
$search](https://www.mongodb.com/docs/search/query/aggregation-stages/search.md#mongodb-pipeline-pipe.-search to perform the following tasks:-
Queries using the following
compoundoperator clauses: -
mustclause with the [range](https://www.mongodb.com/docs/search/query/operators-collectors/range.md#std-label-range-ref operator to search for movies between the years2013to2015. -
shouldclause with the [text](https://www.mongodb.com/docs/search/query/operators-collectors/text.md#std-label-text-ref operator to query for the termsnowin thetitlefield and alter thescorewith theboostoption. Theboostoption multiplies the base score in the results for the search term by2. -
Specifies the [highlight](https://www.mongodb.com/docs/search/query/highlighting.md#std-label-highlight-ref option to return snippets of text from the
titlefield that match the query. The snippets contain matching text specified withtype: 'hit', and adjacent text specified withtype: 'text'.
-
-
[
$limit](https://www.mongodb.com/docs/manual/reference/operator/aggregation/limit.md#mongodb-pipeline-pipe.-limit stage to limit the output to 10 results -
[
$project](https://www.mongodb.com/docs/manual/reference/operator/aggregation/project.md#mongodb-pipeline-pipe.-project stage to:-
Exclude all fields except
titleandyear -
Add two fields named
scoreandhighlights
-
| Pipeline Stage | Query |
|---|---|
$search |
`{ |
| “index”: “default”, | |
| “compound”: { | |
| “must”: [{ | |
| “range”: { | |
| “path”: “year”, | |
| “gte”: 2013, | |
| “lte”: 2015 | |
| } | |
| }], | |
| “should”: [{ | |
| “text”: { | |
| “query”: “snow”, | |
| “path”: “title”, | |
| “score”: {“boost”: {“value”: 2}} | |
| } | |
| }] | |
| }, | |
| “highlight”: { “path”: “title” } | |
| }` | |
$limit |
10 |
$project |
`{ |
| “_id”: 0, | |
| “title”: 1, | |
| “year”: 1, | |
| “score”: { “$meta”: “searchScore” }, | |
| “highlights”: { “$meta”: “searchHighlights” } | |
| }` |
If you [enabled](https://www.mongodb.com/docs/compass/current/aggregation-pipeline-builder/#set-the-documents-limit-or-auto-preview-documents Auto Preview, MongoDB Compass displays the following documents next to the $project pipeline stage:
### Simple Example
json
{
title: 'Snow in Paradise',
year: 2014,
score: 6.7722930908203125,
highlights: [{
score: 1.382846713066101,
path: 'title',
texts: [
{ value: 'Snow', type: 'hit' },
{ value: ' in Paradise', type: 'text' }
]
}]
},
{
title: 'Snow on the Blades',
year: 2014,
score: 6.063445568084717,
highlights: [{
score: 1.3766303062438965,
path: 'title',
texts: [
{ value: 'Snow', type: 'hit' },
{ value: ' on the Blades', type: 'text' }
]
}]
},
{
title: 'The Snow White Murder Case',
year: 2014,
score: 5.509652137756348,
highlights: [{
score: 1.3525336980819702,
path: 'title',
texts: [
{ value: 'The ', type: 'text' },
{ value: 'Snow', type: 'hit' },
{ value: ' White Murder Case', type: 'text' }
]
}]
},
{
title: 'Dead Snow 2: Red vs. Dead',
year: 2014,
score: 5.065053939819336,
highlights: [{
score: 1.3924485445022583,
path: 'title',
texts: [
{ value: 'Dead ', type: 'text' },
{ value: 'Snow', type: 'hit' },
{ value: ' 2: Red vs. ', type: 'text' }
]
}]
},
{ year: 2013, title: 'The Secret Life of Walter Mitty',score: 1, highlights: [] },
{ title: 'Jurassic World', year: 2015, score: 1, highlights: [] },
{ title: 'Action Jackson', year: 2014, score: 1, highlights: [] },
{ year: 2013, title: 'In Secret', score: 1, highlights: [] },
{ title: 'The Stanford Prison Experiment', year: 2015, score: 1, highlights: [] },
{ year: 2014, title: 'The Giver', score: 1, highlights: [] }
The first four documents in the results have a higher score because the should clause in the query specifies a preference for documents with snow in the title. The should clause also alters the score for the query term snow using the boost option.
-
Run a MongoDB Search compound query that alters the score using the [
function](https://www.mongodb.com/docs/search/query/score/modify-score.md#std-label-scoring-function option. The query uses the following pipeline stages: -
[
$search](https://www.mongodb.com/docs/search/query/aggregation-stages/search.md#mongodb-pipeline-pipe.-search stage to perform the following tasks:-
Queries using the following
compoundoperator clauses: -
mustclause with the [range](https://www.mongodb.com/docs/search/query/operators-collectors/range.md#std-label-range-ref operator to search for movies between the years2013to2015. -
shouldclause with the [text](https://www.mongodb.com/docs/search/query/operators-collectors/text.md#std-label-text-ref operator to query for the termsnowin thetitlefield and alter thescorewith thefunctionoption. Thefunctionoption adds the following using an arithmetic expression:-
The relevance score of the query for the search term
-
The value of the numeric field named
imdb.ratingor the number2for those documents that do not have theimdb.ratingfield.
-
-
Specifies the [highlight](https://www.mongodb.com/docs/search/query/highlighting.md#std-label-highlight-ref option to return snippets of text from the
titlefield that match the query. The snippets contain matching text specified withtype: 'hit', and adjacent text specified withtype: 'text'.
-
-
[
$limit](https://www.mongodb.com/docs/manual/reference/operator/aggregation/limit.md#mongodb-pipeline-pipe.-limit stage to limit the output to 10 results -
[
$project](https://www.mongodb.com/docs/manual/reference/operator/aggregation/project.md#mongodb-pipeline-pipe.-project stage to:-
Exclude all fields except
titleandyear -
Add two fields named
scoreandhighlights
-
To run this query in MongoDB Compass:
Click the Aggregations tab.
Click Select..., then configure each of the following pipeline stages by selecting the stage from the dropdown and adding the query for that stage. Click Add Stage to add additional stages.
| Pipeline Stage | Query |
|---|---|
$search |
`{ |
| “index”: “default”, | |
| “compound”: { | |
| “must”: [{ | |
| “range”: { | |
| “path”: “year”, | |
| “gte”: 2013, | |
| “lte”: 2015 | |
| } | |
| }], | |
| “should”: [{ | |
| “text”: { | |
| “query”: “snow”, | |
| “path”: “title”, | |
| “score”: { | |
| “function”: { | |
| “add”: [{ | |
| “path”: { | |
| “value”: “imdb.rating”, | |
| “undefined”: 2 | |
| } | |
| }, | |
| { | |
| “score”: “relevance” | |
| }] | |
| } | |
| } | |
| } | |
| }]}, | |
| “highlight”:{ “path”: “title” } | |
| }` | |
$limit |
10 |
$project |
`{ |
| “_id”: 0, | |
| “title”: 1, | |
| “year”: 1, | |
| “score”: { “$meta”: “searchScore” }, | |
| “highlights”: { “$meta”: “searchHighlights” } | |
| }` |
If you [enabled](https://www.mongodb.com/docs/compass/current/aggregation-pipeline-builder/#set-the-documents-limit-or-auto-preview-documents Auto Preview, MongoDB Compass displays the following documents next to the $project pipeline stage:
json
{
title: 'The Snow White Murder Case',
year: 2014,
score: 10.454826354980469,
highlights: [{
score: 1.3525336980819702,
path: 'title',
texts: [
{ value: 'The ', type: 'text' },
{ value: 'Snow', type: 'hit' },
{ value: ' White Murder Case', type: 'text' }
]
}]
},
{
title: 'Snow on the Blades',
year: 2014,
score: 10.3317232131958,
highlights: [{
score: 1.3766303062438965,
path: 'title',
texts: [
{ value: 'Snow', type: 'hit' },
{ value: ' on the Blades', type: 'text' }
]
}]
},
{
title: 'Dead Snow 2: Red vs. Dead',
year: 2014,
score: 10.032526969909668,
highlights: [{
score: 1.3924485445022583,
path: 'title',
texts: [
{ value: 'Dead ', type: 'text' },
{ value: 'Snow', type: 'hit' },
{ value: ' 2: Red vs. ', type: 'text' }
]
}]
},
{
title: 'Snow in Paradise',
year: 2014,
score: 8.386146545410156,
highlights: [{
score: 1.382846713066101,
path: 'title',
texts: [
{ value: 'Snow', type: 'hit' },
{ value: ' in Paradise', type: 'text' }
]
}]
},
{ year: 2013, title: 'The Secret Life of Walter Mitty', score: 1, highlights: [] },
{ title: 'Jurassic World', year: 2015, score: 1, highlights: [] },
{ title: 'Action Jackson', year: 2014, score: 1, highlights: [] },
{ year: 2013, title: 'In Secret', score: 1, highlights: [] },
{ title: 'The Stanford Prison Experiment', year: 2015, score: 1, highlights: [] },
{ year: 2014, title: 'The Giver', score: 1, highlights: [] }
The first four documents in the results have a higher score because the should clause in the query specifies a preference for documents with snow in the title. The should clause also alters the score for the query term snow using the function option.
1) Run a MongoDB Search compound query that alters the score using the [constant](https://www.mongodb.com/docs/search/query/score/modify-score.md#std-label-scoring-constant option.
Create a new directory called compound-constant-example and initialize your project with the dotnet new command.
bash
mkdir compound-constant-example
cd compound-constant-example
dotnet new console
Add the .NET/C# driver to your project as a dependency.
bash
dotnet add package MongoDB.Driver
Replace the contents of the Program.cs file with the following code.
The code example performs the following tasks:
-
Imports
mongodbpackages and dependencies. -
Establishes a connection to your cluster.
-
Uses the following compound clauses to query the collection:
-
filterclause with the [range](https://www.mongodb.com/docs/search/query/operators-collectors/range.md#std-label-range-ref operator to search for movies between the years2013to2015. -
shouldclause with the [text](https://www.mongodb.com/docs/search/query/operators-collectors/text.md#std-label-text-ref operator to query for the termsnowin thetitlefield and alter thescorewith theconstantoption. Theconstantoption replaces all score results for the search term with5.
-
-
Specifies the [highlight](https://www.mongodb.com/docs/search/query/highlighting.md#std-label-highlight-ref option to return snippets of text from the
titlefield that match the query. The snippets contain matching text specified withtype: 'hit', and adjacent text specified withtype: 'text'. -
Uses the following pipeline stages:
-
[
$limit](https://www.mongodb.com/docs/manual/reference/operator/aggregation/limit.md#mongodb-pipeline-pipe.-limit stage to limit the output to 10 results -
[
$project](https://www.mongodb.com/docs/manual/reference/operator/aggregation/project.md#mongodb-pipeline-pipe.-project stage to: -
Exclude all fields except
titleandyear -
Add two fields named
scoreandhighlights
-
-
Iterates over the cursor to print the documents that match the query.
```csharp using MongoDB.Bson; using MongoDB.Bson.Serialization.Attributes; using MongoDB.Bson.Serialization.Conventions; using MongoDB.Driver; using MongoDB.Driver.Search;
public class CompoundConstantExample
{
private const string MongoConnectionString = "
public static void Main(string[] args)
{
// allow automapping of the camelCase database fields to our MovieDocument
var camelCaseConvention = new ConventionPack { new CamelCaseElementNameConvention() };
ConventionRegistry.Register("CamelCase", camelCaseConvention, type => true);
// connect to your Atlas cluster
var mongoClient = new MongoClient(MongoConnectionString);
var mflixDatabase = mongoClient.GetDatabase("sample_mflix");
var moviesCollection = mflixDatabase.GetCollection<MovieDocument>("movies");
// define and run pipeline
var results = moviesCollection.Aggregate()
.Search(Builders<MovieDocument>.Search.Compound()
.Filter(Builders<MovieDocument>.Search.Range(movie => movie.Year, SearchRangeBuilder.Gte(2013).Lte(2015)))
.Should(Builders<MovieDocument>.Search.Text(movie => movie.Title, "snow", score: new SearchScoreDefinitionBuilder<MovieDocument>().Constant(5))),
new SearchHighlightOptions<MovieDocument>(movie => movie.Title),
indexName: "default")
.Project<MovieDocument>(Builders<MovieDocument>.Projection
.Include(movie => movie.Title)
.Include(movie => movie.Year)
.Exclude(movie => movie.Id)
.MetaSearchScore(movie => movie.Score)
.MetaSearchHighlights("highlights"))
.Limit(10)
.ToList();
// print results
foreach (var movie in results)
{
Console.WriteLine(movie.ToJson());
}
}
}
[BsonIgnoreExtraElements]
public class MovieDocument
{
[BsonIgnoreIfDefault]
public ObjectId Id { get; set; }
public string Title { get; set; }
public int Year { get; set; }
[BsonElement("highlights")]
public List
```
Before you run the sample, replace <connection-string> with your Atlas connection string. Ensure that your connection string includes your database user's credentials. To learn more, see [Connect to a Cluster via Client Libraries.](https://www.mongodb.com/docs/atlas/driver-connection.md#std-label-connect-via-driver
Compile and run the Program.cs file.
bash
dotnet run compound-constant-example.csproj
Output:
json
{
"title" : "Snow in Paradise",
"year" : 2014,
"highlights" : [{
"path" : "title",
"score" : 1.3828467130661011,
"texts" : [{ "type" : "Hit", "value" : "Snow" }, { "type" : "Text", "value" : " in Paradise" }]
}],
"score" : 5.0
}
{
"title" : "Dead Snow 2: Red vs. Dead",
"year" : 2014,
"highlights" : [{
"path" : "title",
"score" : 1.3924485445022583,
"texts" : [{ "type" : "Text", "value" : "Dead " }, { "type" : "Hit", "value" : "Snow" }, { "type" : "Text", "value" : " 2: Red vs. " }]
}],
"score" : 5.0
}
{
"title" : "The Snow White Murder Case",
"year" : 2014,
"highlights" : [{
"path" : "title",
"score" : 1.3525336980819702,
"texts" : [{ "type" : "Text", "value" : "The " }, { "type" : "Hit", "value" : "Snow" }, { "type" : "Text", "value" : " White Murder Case" }]
}],
"score" : 5.0
}
{
"title" : "Snow on the Blades",
"year" : 2014,
"highlights" : [{
"path" : "title",
"score" : 1.3766303062438965,
"texts" : [{ "type" : "Hit", "value" : "Snow" }, { "type" : "Text", "value" : " on the Blades" }]
}],
"score" : 5.0
}
{ "title" : "The Secret Life of Walter Mitty", "year" : 2013, "highlights" : [], "score" : 0.0 }
{ "title" : "Jurassic World", "year" : 2015, "highlights" : [], "score" : 0.0 }
{ "title" : "Action Jackson", "year" : 2014, "highlights" : [], "score" : 0.0 }
{ "title" : "In Secret", "year" : 2013, "highlights" : [], "score" : 0.0 }
{ "title" : "The Stanford Prison Experiment", "year" : 2015, "highlights" : [], "score" : 0.0 }
{ "title" : "The Giver", "year" : 2014, "highlights" : [], "score" : 0.0 }
The first four documents in the results have a higher score because the should clause in the query specifies a preference for documents with snow in the title. The should clause also alters the score for the query term snow using the constant option.
2) Run MongoDB Search compound queries that alter the score using the [boost](https://www.mongodb.com/docs/search/query/score/modify-score.md#std-label-scoring-boost option.
Create a new directory called compound-boost-example and initialize your project with the dotnet new command.
bash
mkdir compound-boost-example
cd compound-boost-example
dotnet new console
Add the .NET/C# driver to your project as a dependency.
bash
dotnet add package MongoDB.Driver
Replace the contents of the Program.cs file with the following code.
The code example performs the following tasks:
-
Imports
mongodbpackages and dependencies. -
Establishes a connection to your cluster.
-
Iterates over the cursor to print the documents that match the query.
### Simple Example
The query uses the following pipeline stages:
-
[
$search](https://www.mongodb.com/docs/search/query/aggregation-stages/search.md#mongodb-pipeline-pipe.-search stage to query the collection. The query:-
Uses the following
compoundoperator clauses: -
mustclause with the [range](https://www.mongodb.com/docs/search/query/operators-collectors/range.md#std-label-range-ref operator to search for movies between the years2013to2015. -
shouldclause with the [text](https://www.mongodb.com/docs/search/query/operators-collectors/text.md#std-label-text-ref operator to query for the termsnowin thetitlefield and alter thescorewith theboostoption. Theboostoption multiplies the base score in the results for the search term by2.
Specifies the [highlight](https://www.mongodb.com/docs/search/query/highlighting.md#std-label-highlight-ref option to return snippets of text from the
titlefield that match the query. The snippets contain matching text specified withtype: 'hit', and adjacent text specified withtype: 'text'. -
-
[
$limit](https://www.mongodb.com/docs/manual/reference/operator/aggregation/limit.md#mongodb-pipeline-pipe.-limit stage to limit the output to 10 results -
[
$project](https://www.mongodb.com/docs/manual/reference/operator/aggregation/project.md#mongodb-pipeline-pipe.-project stage to:-
Exclude all fields except
titleandyear -
Add two fields named
scoreandhighlights
-
```csharp using MongoDB.Bson; using MongoDB.Bson.Serialization.Attributes; using MongoDB.Bson.Serialization.Conventions; using MongoDB.Driver; using MongoDB.Driver.Search;
public class CompoundBoostSingleExample
{
private const string MongoConnectionString = "
public static void Main(string[] args)
{
// allow automapping of the camelCase database fields to our MovieDocument
var camelCaseConvention = new ConventionPack { new CamelCaseElementNameConvention() };
ConventionRegistry.Register("CamelCase", camelCaseConvention, type => true);
// connect to your Atlas cluster
var mongoClient = new MongoClient(MongoConnectionString);
var mflixDatabase = mongoClient.GetDatabase("sample_mflix");
var moviesCollection = mflixDatabase.GetCollection<MovieDocument>("movies");
// define and run pipeline
var results = moviesCollection.Aggregate()
.Search(Builders<MovieDocument>.Search.Compound()
.Must(Builders<MovieDocument>.Search.Range(movie => movie.Year, SearchRangeBuilder.Gte(2013).Lte(2015)))
.Should(Builders<MovieDocument>.Search.Text(movie => movie.Title, "snow", score: new SearchScoreDefinitionBuilder<MovieDocument>().Boost(2))),
new SearchHighlightOptions<MovieDocument>(movie => movie.Title),
indexName: "default")
.Project<MovieDocument>(Builders<MovieDocument>.Projection
.Include(movie => movie.Title)
.Include(movie => movie.Year)
.Exclude(movie => movie.Id)
.MetaSearchScore(movie => movie.Score)
.MetaSearchHighlights("highlights"))
.Limit(10)
.ToList();
// print results
foreach (var movie in results)
{
Console.WriteLine(movie.ToJson());
}
}
}
[BsonIgnoreExtraElements]
public class MovieDocument
{
[BsonIgnoreIfDefault]
public ObjectId Id { get; set; }
public string Title { get; set; }
public int Year { get; set; }
[BsonElement("highlights")]
public List
```
Before you run the sample, replace <connection-string> with your Atlas connection string. Ensure that your connection string includes your database user's credentials. To learn more, see [Connect to a Cluster via Client Libraries.](https://www.mongodb.com/docs/atlas/driver-connection.md#std-label-connect-via-driver
Compile and run the Program.cs file.
### Simple Example
bash
dotnet run compound-boost-example.csproj
Output:
json
{
"title" : "Snow in Paradise",
"year" : 2014,
"highlights" : [{
"path" : "title",
"score" : 1.3828467130661011,
"texts" : [{ "type" : "Hit", "value" : "Snow" }, { "type" : "Text", "value" : " in Paradise" }]
}],
"score" : 6.7722930908203125
}
{
"title" : "Snow on the Blades",
"year" : 2014,
"highlights" : [{
"path" : "title",
"score" : 1.3766303062438965,
"texts" : [{ "type" : "Hit", "value" : "Snow" }, { "type" : "Text", "value" : " on the Blades" }]
}],
"score" : 6.0634455680847168
}
{
"title" : "The Snow White Murder Case",
"year" : 2014,
"highlights" : [{
"path" : "title",
"score" : 1.3525336980819702,
"texts" : [{ "type" : "Text", "value" : "The " }, { "type" : "Hit", "value" : "Snow" }, { "type" : "Text", "value" : " White Murder Case" }]
}],
"score" : 5.5096521377563477
}
{
"title" : "Dead Snow 2: Red vs. Dead",
"year" : 2014,
"highlights" : [{
"path" : "title",
"score" : 1.3924485445022583,
"texts" : [{ "type" : "Text", "value" : "Dead " }, { "type" : "Hit", "value" : "Snow" }, { "type" : "Text", "value" : " 2: Red vs. " }]
}],
"score" : 5.0650539398193359
}
{ "title" : "The Secret Life of Walter Mitty", "year" : 2013, "highlights" : [], "score" : 1.0 }
{ "title" : "Jurassic World", "year" : 2015, "highlights" : [], "score" : 1.0 }
{ "title" : "Action Jackson", "year" : 2014, "highlights" : [], "score" : 1.0 }
{ "title" : "In Secret", "year" : 2013, "highlights" : [], "score" : 1.0 }
{ "title" : "The Stanford Prison Experiment", "year" : 2015, "highlights" : [], "score" : 1.0 }
{ "title" : "The Giver", "year" : 2014, "highlights" : [], "score" : 1.0 }
The first four documents in the results have a higher score because the should clause in the query specifies a preference for documents with snow in the title. The should clause also alters the score for the query term snow using the boost option.
3) Run a MongoDB Search compound query that alters the score using the [function](https://www.mongodb.com/docs/search/query/score/modify-score.md#std-label-scoring-function option.
Create a new directory called compound-function-example and initialize your project with the dotnet new command.
bash
mkdir compound-function-example
cd compound-function-example
dotnet new console
Add the .NET/C# driver to your project as a dependency.
bash
dotnet add package MongoDB.Driver
Replace the contents of the Program.cs file with the following code.
The code example performs the following tasks:
-
Imports
mongodbpackages and dependencies. -
Establishes a connection to your cluster.
-
Uses the following pipeline stages to query the collection:
-
mustclause with the [range](https://www.mongodb.com/docs/search/query/operators-collectors/range.md#std-label-range-ref operator to search for movies between the years2013to2015. -
shouldclause with the [text](https://www.mongodb.com/docs/search/query/operators-collectors/text.md#std-label-text-ref operator to query for the termsnowin thetitlefield and alter thescorewith thefunctionoption. Thefunctionoption adds the following using an a
-
(本文超出站点单文档体积上限,已截断)
