For AI agents: a documentation index is available at https://www.mongodb.com/docs/llms.txt — markdown versions of all pages are available by appending .md to any URL path.
Docs Menu

Customize the Score of the Documents in the Results

You can customize the score 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. This page demonstrates how to:

  • Modify the score of the documents in the results to boost or bury the results.

  • Normalize your $search query score in the range from 0 to 1 in the subsequent stages of your aggregation pipeline.

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.

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:

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.

You can set up an index with 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.

The sample queries demonstrate how to boost or bury the documents in the results. They use the compound operator to combine two or more operators into a single query.

1

You can go the MongoDB Search page from the Search & Vector Search option, or the Data Explorer.

  1. If it's not already displayed, select the organization that contains your project from the Organizations menu in the navigation bar.

  2. If it's not already displayed, select your project from the Projects menu in the navigation bar.

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

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

2

Click the Query button to the right of the index to query.

3

Click Edit Query to view a default query syntax sample in JSON format.

4

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.

The following query:

  • Uses the following compound operator clauses:

    • filter clause with the range operator to search for movies between the years 2013 to 2015.

    • should clause with the text operator to query for the term snow in the title field and alter the score with the constant option. The constant option replaces all score results for the search term with 5.

  • Specifies the highlight option to return snippets of text from the title field that match the query. The snippets contain matching text specified with type: 'hit', and adjacent text specified with type: 'text'.

[
{
$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"
}
}
}
]
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.

5

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

Open mongosh in a terminal window and connect to your cluster. For detailed instructions on connecting, see Connect to a Cluster via mongosh.

2

Run the following command at mongosh prompt:

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.

This query uses the following pipeline stages:

  • $search to query the collection. The query:

    • Uses the following compound operator clauses:

      • filter clause with the range operator to search for movies between the years 2013 to 2015.

      • should clause with the text operator to query for the term snow in the title field and alter the score with the constant option. The constant option replaces all score results for the search term with 5.

    • Specifies the highlight option to return snippets of text from the title field that match the query. The snippets contain matching text specified with type: 'hit', and adjacent text specified with type: 'text'.

  • $limit stage to limit the output to 10 results.

  • $project stage to:

    • Exclude all fields except title and year

    • Add a score field

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:

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

1

Open MongoDB Compass and connect to your cluster. For detailed instructions on connecting, see Connect to a Cluster via Compass.

2

On the Database screen, click the sample_mflix database, then click the movies collection.

3

Run a MongoDB Search compound query that alters the score using the constant option. The query performs the following tasks:

  • Uses the following compound operator clauses:

    • filter clause with the range operator to search for movies between the years 2013 to 2015.

    • should clause with the text operator to query for the term snow in the title field and alter the score with the constant option. The constant option replaces all score results for the search term with 5.

  • Specifies the highlight option to return snippets of text from the title field that match the query. The snippets contain matching text specified with type: 'hit', and adjacent text specified with type: 'text'.

  • Uses the following pipeline stages:

    • $limit stage to limit the output to 10 results

    • $project stage to:

      • Exclude all fields except title and year

      • Add two fields named score and highlights

To run this query in MongoDB Compass:

  1. Click the Aggregations tab.

  2. 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 Auto Preview, MongoDB Compass displays the following documents next to the $project pipeline stage:

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

4
  1. Click the Aggregations tab.

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

    The query uses the following pipeline stages:

    • $search to perform the following tasks:

      • Queries using the following compound operator clauses:

        • must clause with the range operator to search for movies between the years 2013 to 2015.

        • should clause with the text operator to query for the term snow in the title field and alter the score with the boost option. The boost option multiplies the base score in the results for the search term by 2.

      • Specifies the highlight option to return snippets of text from the title field that match the query. The snippets contain matching text specified with type: 'hit', and adjacent text specified with type: 'text'.

    • $limit stage to limit the output to 10 results

    • $project stage to:

      • Exclude all fields except title and year

      • Add two fields named score and highlights

    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 Auto Preview, MongoDB Compass displays the following documents next to the $project pipeline stage:

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

5

Run a MongoDB Search compound query that alters the score using the function option. The query uses the following pipeline stages:

  • $search stage to perform the following tasks:

    • Queries using the following compound operator clauses:

      • must clause with the range operator to search for movies between the years 2013 to 2015.

      • should clause with the text operator to query for the term snow in the title field and alter the score with the function option. The function option 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.rating or the number 2 for those documents that do not have the imdb.rating field.

    • Specifies the highlight option to return snippets of text from the title field that match the query. The snippets contain matching text specified with type: 'hit', and adjacent text specified with type: 'text'.

  • $limit stage to limit the output to 10 results

  • $project stage to:

    • Exclude all fields except title and year

    • Add two fields named score and highlights

To run this query in MongoDB Compass:

  1. Click the Aggregations tab.

  2. 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 Auto Preview, MongoDB Compass displays the following documents next to the $project pipeline stage:

    {
    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
  1. Create a new directory called compound-constant-example and initialize your project with the dotnet new command.

    mkdir compound-constant-example
    cd compound-constant-example
    dotnet new console
  2. Add the .NET/C# driver to your project as a dependency.

    dotnet add package MongoDB.Driver
  3. Replace the contents of the Program.cs file with the following code.

    The code example performs the following tasks:

    • Imports mongodb packages and dependencies.

    • Establishes a connection to your cluster.

    • Uses the following compound clauses to query the collection:

      • filter clause with the range operator to search for movies between the years 2013 to 2015.

      • should clause with the text operator to query for the term snow in the title field and alter the score with the constant option. The constant option replaces all score results for the search term with 5.

    • Specifies the highlight option to return snippets of text from the title field that match the query. The snippets contain matching text specified with type: 'hit', and adjacent text specified with type: 'text'.

    • Uses the following pipeline stages:

      • $limit stage to limit the output to 10 results

      • $project stage to:

        • Exclude all fields except title and year

        • Add two fields named score and highlights

    • Iterates over the cursor to print the documents that match the query.

    1using MongoDB.Bson;
    2using MongoDB.Bson.Serialization.Attributes;
    3using MongoDB.Bson.Serialization.Conventions;
    4using MongoDB.Driver;
    5using MongoDB.Driver.Search;
    6
    7public class CompoundConstantExample
    8{
    9 private const string MongoConnectionString = "<connection-string>";
    10
    11 public static void Main(string[] args)
    12 {
    13 // allow automapping of the camelCase database fields to our MovieDocument
    14 var camelCaseConvention = new ConventionPack { new CamelCaseElementNameConvention() };
    15 ConventionRegistry.Register("CamelCase", camelCaseConvention, type => true);
    16
    17 // connect to your Atlas cluster
    18 var mongoClient = new MongoClient(MongoConnectionString);
    19 var mflixDatabase = mongoClient.GetDatabase("sample_mflix");
    20 var moviesCollection = mflixDatabase.GetCollection<MovieDocument>("movies");
    21
    22 // define and run pipeline
    23 var results = moviesCollection.Aggregate()
    24 .Search(Builders<MovieDocument>.Search.Compound()
    25 .Filter(Builders<MovieDocument>.Search.Range(movie => movie.Year, SearchRangeBuilder.Gte(2013).Lte(2015)))
    26 .Should(Builders<MovieDocument>.Search.Text(movie => movie.Title, "snow", score: new SearchScoreDefinitionBuilder<MovieDocument>().Constant(5))),
    27 new SearchHighlightOptions<MovieDocument>(movie => movie.Title),
    28 indexName: "default")
    29 .Project<MovieDocument>(Builders<MovieDocument>.Projection
    30 .Include(movie => movie.Title)
    31 .Include(movie => movie.Year)
    32 .Exclude(movie => movie.Id)
    33 .MetaSearchScore(movie => movie.Score)
    34 .MetaSearchHighlights("highlights"))
    35 .Limit(10)
    36 .ToList();
    37
    38 // print results
    39 foreach (var movie in results)
    40 {
    41 Console.WriteLine(movie.ToJson());
    42 }
    43 }
    44}
    45
    46[BsonIgnoreExtraElements]
    47public class MovieDocument
    48{
    49 [BsonIgnoreIfDefault]
    50 public ObjectId Id { get; set; }
    51 public string Title { get; set; }
    52 public int Year { get; set; }
    53 [BsonElement("highlights")]
    54 public List<SearchHighlight> Highlights { get; set; }
    55 public double Score { get; set; }
    56}
  4. 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.

  5. Compile and run the Program.cs file.

    dotnet run compound-constant-example.csproj
    {
    "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
  1. Create a new directory called compound-boost-example and initialize your project with the dotnet new command.

    mkdir compound-boost-example
    cd compound-boost-example
    dotnet new console
  2. Add the .NET/C# driver to your project as a dependency.

    dotnet add package MongoDB.Driver
  3. Replace the contents of the Program.cs file with the following code.

    The code example performs the following tasks:

    • Imports mongodb packages and dependencies.

    • Establishes a connection to your cluster.

    • Iterates over the cursor to print the documents that match the query.

    The query uses the following pipeline stages:

    • $search stage to query the collection. The query:

      • Uses the following compound operator clauses:

        • must clause with the range operator to search for movies between the years 2013 to 2015.

        • should clause with the text operator to query for the term snow in the title field and alter the score with the boost option. The boost option multiplies the base score in the results for the search term by 2.

      Specifies the highlight option to return snippets of text from the title field that match the query. The snippets contain matching text specified with type: 'hit', and adjacent text specified with type: 'text'.

    • $limit stage to limit the output to 10 results

    • $project stage to:

      • Exclude all fields except title and year

      • Add two fields named score and highlights

    1using MongoDB.Bson;
    2using MongoDB.Bson.Serialization.Attributes;
    3using MongoDB.Bson.Serialization.Conventions;
    4using MongoDB.Driver;
    5using MongoDB.Driver.Search;
    6
    7public class CompoundBoostSingleExample
    8{
    9 private const string MongoConnectionString = "<connection-string>";
    10
    11 public static void Main(string[] args)
    12 {
    13 // allow automapping of the camelCase database fields to our MovieDocument
    14 var camelCaseConvention = new ConventionPack { new CamelCaseElementNameConvention() };
    15 ConventionRegistry.Register("CamelCase", camelCaseConvention, type => true);
    16
    17 // connect to your Atlas cluster
    18 var mongoClient = new MongoClient(MongoConnectionString);
    19 var mflixDatabase = mongoClient.GetDatabase("sample_mflix");
    20 var moviesCollection = mflixDatabase.GetCollection<MovieDocument>("movies");
    21
    22 // define and run pipeline
    23 var results = moviesCollection.Aggregate()
    24 .Search(Builders<MovieDocument>.Search.Compound()
    25 .Must(Builders<MovieDocument>.Search.Range(movie => movie.Year, SearchRangeBuilder.Gte(2013).Lte(2015)))
    26 .Should(Builders<MovieDocument>.Search.Text(movie => movie.Title, "snow", score: new SearchScoreDefinitionBuilder<MovieDocument>().Boost(2))),
    27 new SearchHighlightOptions<MovieDocument>(movie => movie.Title),
    28 indexName: "default")
    29 .Project<MovieDocument>(Builders<MovieDocument>.Projection
    30 .Include(movie => movie.Title)
    31 .Include(movie => movie.Year)
    32 .Exclude(movie => movie.Id)
    33 .MetaSearchScore(movie => movie.Score)
    34 .MetaSearchHighlights("highlights"))
    35 .Limit(10)
    36 .ToList();
    37
    38 // print results
    39 foreach (var movie in results)
    40 {
    41 Console.WriteLine(movie.ToJson());
    42 }
    43 }
    44}
    45
    46[BsonIgnoreExtraElements]
    47public class MovieDocument
    48{
    49 [BsonIgnoreIfDefault]
    50 public ObjectId Id { get; set; }
    51 public string Title { get; set; }
    52 public int Year { get; set; }
    53 [BsonElement("highlights")]
    54 public List<SearchHighlight> Highlights { get; set; }
    55 public double Score { get; set; }
    56}
  4. 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.

  5. Compile and run the Program.cs file.

    dotnet run compound-boost-example.csproj
    {
    "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
  1. Create a new directory called compound-function-example and initialize your project with the dotnet new command.

    mkdir compound-function-example
    cd compound-function-example
    dotnet new console
  2. Add the .NET/C# driver to your project as a dependency.

    dotnet add package MongoDB.Driver
  3. Replace the contents of the Program.cs file with the following code.

    The code example performs the following tasks:

    • Imports mongodb packages and dependencies.

    • Establishes a connection to your cluster.

    • Uses the following pipeline stages to query the collection:

      • must clause with the range operator to search for movies between the years 2013 to 2015.

      • should clause with the text operator to query for the term snow in the title field and alter the score with the function option. The function option 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.rating or the number 2 for those documents that do not have the imdb.rating field.

    • Uses the following pipeline stages:

      • $limit stage to limit the output to 10 results

      • $project stage to:

        • Exclude all fields except title and year

        • Add two fields named score and highlights

    • Specifies the highlight option to return snippets of text from the title field that match the query. The snippets contain matching text specified with type: 'hit', and adjacent text specified with type: 'text'.

    • Iterates over the cursor to print the documents that match the query.

    1using MongoDB.Bson;
    2using MongoDB.Bson.Serialization.Attributes;
    3using MongoDB.Bson.Serialization.Conventions;
    4using MongoDB.Driver;
    5using MongoDB.Driver.Search;
    6
    7public class CompoundFunctionExample
    8{
    9 private const string MongoConnectionString = "<connection-string>";
    10
    11 public static void Main(string[] args)
    12 {
    13 // allow automapping of the camelCase database fields to our MovieDocument
    14 var camelCaseConvention = new ConventionPack { new CamelCaseElementNameConvention() };
    15 ConventionRegistry.Register("CamelCase", camelCaseConvention, type => true);
    16
    17 // connect to your Atlas cluster
    18 var mongoClient = new MongoClient(MongoConnectionString);
    19 var mflixDatabase = mongoClient.GetDatabase("sample_mflix");
    20 var moviesCollection = mflixDatabase.GetCollection<MovieDocument>("movies");
    21
    22 var scoreFunction = Builders<MovieDocument>.SearchScore.Function(Builders<MovieDocument>.SearchScoreFunction.Add(Builders<MovieDocument>.SearchScoreFunction.Path(movie => movie.Imdb.Rating, 2), Builders<MovieDocument>.SearchScoreFunction.Relevance()));
    23 // define and run pipeline
    24 var results = moviesCollection.Aggregate()
    25 .Search(Builders<MovieDocument>.Search.Compound()
    26 .Must(Builders<MovieDocument>.Search.Range(movie => movie.Year, SearchRangeBuilder.Gte(2013).Lte(2015)))
    27 .Should(Builders<MovieDocument>.Search.Text(movie => movie.Title, "snow", score: scoreFunction)),
    28 new SearchHighlightOptions<MovieDocument>(movie => movie.Title),
    29 indexName: "default")
    30 .Project<MovieDocument>(Builders<MovieDocument>.Projection
    31 .Include(movie => movie.Genres)
    32 .Include(movie => movie.Title)
    33 .Include(movie => movie.Year)
    34 .Exclude(movie => movie.Id)
    35 .MetaSearchScore(movie => movie.Score)
    36 .MetaSearchHighlights("highlights"))
    37 .Limit(10)
    38 .ToList();
    39
    40 // print results
    41 foreach (var movie in results)
    42 {
    43 Console.WriteLine(movie.ToJson());
    44 }
    45 }
    46}
    47
    48[BsonIgnoreExtraElements]
    49public class MovieDocument
    50{
    51 [BsonIgnoreIfDefault]
    52 public ObjectId Id { get; set; }
    53 public string [] Genres { get; set; }
    54 public IMDB Imdb { get; set; }
    55 public string Title { get; set; }
    56 public int Year { get; set; }
    57 [BsonElement("highlights")]
    58 public List<SearchHighlight> Highlights { get; set; }
    59 public double Score { get; set; }
    60}
    61
    62[BsonIgnoreExtraElements]
    63public class IMDB
    64{
    65 public double Rating { get; set; }
    66}
  4. 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.

  5. Compile and run the Program.cs file.

    dotnet run compound-function-example.csproj
    { "genres" : ["Drama", "Mystery"], "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" : 10.454826354980469 }
    { "genres" : ["Action", "Drama", "History"], "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" : 10.331723213195801 }
    { "genres" : ["Action", "Comedy", "Horror"], "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" : 10.032526969909668 }
    { "genres" : ["Thriller"], "title" : "Snow in Paradise", "year" : 2014, "highlights" : [{ "path" : "title", "score" : 1.3828467130661011, "texts" : [{ "type" : "Hit", "value" : "Snow" }, { "type" : "Text", "value" : " in Paradise" }] }], "score" : 8.3861465454101562 }
    { "genres" : ["Adventure", "Comedy", "Drama"], "title" : "The Secret Life of Walter Mitty", "year" : 2013, "highlights" : [], "score" : 1.0 }
    { "genres" : ["Action", "Adventure", "Sci-Fi"], "title" : "Jurassic World", "year" : 2015, "highlights" : [], "score" : 1.0 }
    { "genres" : ["Action", "Comedy", "Drama"], "title" : "Action Jackson", "year" : 2014, "highlights" : [], "score" : 1.0 }
    { "genres" : ["Crime", "Drama", "Thriller"], "title" : "In Secret", "year" : 2013, "highlights" : [], "score" : 1.0 }
    { "genres" : ["Drama", "Thriller"], "title" : "The Stanford Prison Experiment", "year" : 2015, "highlights" : [], "score" : 1.0 }
    { "genres" : ["Drama", "Sci-Fi"], "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 function option.

1
  1. Create a file named compound-constant-query.go.

  2. Copy and paste the code example into the compound-constant-query.go file.

    The code example performs the following tasks:

    • Imports mongodb packages and dependencies.

    • Establishes a connection to your cluster.

    • Uses the following compound clauses to query the collection:

      • filter clause with the range operator to search for movies between the years 2013 to 2015.

      • should clause with the text operator to query for the term snow in the title field and alter the score with the constant option. The constant option replaces all score results for the search term with 5.

    • Specifies the highlight option to return snippets of text from the title field that match the query. The snippets contain matching text specified with type: 'hit', and adjacent text specified with type: 'text'.

    • Uses the following pipeline stages:

      • $limit stage to limit the output to 10 results

      • $project stage to:

        • Exclude all fields except title and year

        • Add two fields named score and highlights

    • Iterates over the cursor to print the documents that match the query.

    1package main
    2
    3import (
    4 "context"
    5 "fmt"
    6 "time"
    7
    8 "go.mongodb.org/mongo-driver/v2/bson"
    9 "go.mongodb.org/mongo-driver/v2/mongo"
    10 "go.mongodb.org/mongo-driver/v2/mongo/options"
    11)
    12
    13func main() {
    14 // connect to the Atlas cluster and set a maximum operation time
    15 opts := options.Client().
    16 SetTimeout(5 * time.Second).
    17 ApplyURI("<connection-string>")
    18
    19 client, err := mongo.Connect(opts)
    20 if err != nil {
    21 panic(err)
    22 }
    23 defer client.Disconnect(context.TODO())
    24
    25 // set namespace
    26 collection := client.Database("sample_mflix").Collection("movies")
    27
    28 // define pipeline stages
    29 searchStage := bson.D{{"$search", bson.M{
    30 "index": "default",
    31 "compound": bson.M{
    32 "filter": bson.M{
    33 "range": bson.M{
    34 "path": "year", "gte": 2013, "lte": 2015,
    35 },
    36 },
    37 "should": bson.D{
    38 {"text", bson.M{
    39 "path": "title", "query": "snow", "score": bson.M{
    40 "constant": bson.D{{"value", 5}},
    41 }}}},
    42 },
    43 "highlight": bson.D{{"path", "title"}},
    44 }}}
    45 limitStage := bson.D{{"$limit", 10}}
    46 projectStage := bson.D{{"$project", bson.D{{"title", 1}, {"year", 1}, {"_id", 0}, {"score", bson.D{{"$meta", "searchScore"}}}, {"highlights", bson.D{{"$meta", "searchHighlights"}}}}}}
    47
    48 // run pipeline
    49 cursor, err := collection.Aggregate(context.TODO(), mongo.Pipeline{searchStage, limitStage, projectStage})
    50 if err != nil {
    51 panic(err)
    52 }
    53
    54 // print results
    55 var results []bson.D
    56 if err = cursor.All(context.TODO(), &results); err != nil {
    57 panic(err)
    58 }
    59 for _, result := range results {
    60 fmt.Println(result)
    61 }
    62}
  3. 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.

  4. Run the following command to query your collection:

    go run compound-constant-query.go
    [{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.

2
  1. Create a file named compound-boost-query.go.

  2. Copy and paste the code example into the compound-boost-query.go file.

    The code examples perform the following tasks:

    • Imports mongodb packages and dependencies.

    • Establishes a connection to your cluster.

    • Iterates over the cursor to print the documents that match the query.

    The query uses the following pipeline stages:

    • $search stage to query the collection. The query:

      • Uses the following compound clauses to query the collection:

        • must clause with the range operator to search for movies between the years 2013 to 2015.

        • should clause with the text operator to query for the term snow in the title field and alter the score with the boost option. The boost option multiplies the base score in the results for the search term by 2.

      • Specifies the highlight option to return snippets of text from the title field that match the query. The snippets contain matching text specified with type: 'hit', and adjacent text specified with type: 'text'.

    • $limit stage to limit the output to 10 results

    • $project stage to:

      • Exclude all fields except title and year

      • Add two fields named score and highlights

    1package main
    2
    3import (
    4 "context"
    5 "fmt"
    6 "time"
    7
    8 "go.mongodb.org/mongo-driver/v2/bson"
    9 "go.mongodb.org/mongo-driver/v2/mongo"
    10 "go.mongodb.org/mongo-driver/v2/mongo/options"
    11)
    12
    13// define structure of movies collection
    14type MovieCollection struct {
    15 title string `bson:"Title,omitempty"`
    16}
    17
    18func main() {
    19 var err error
    20 // connect to the Atlas cluster and set a maximum operation time
    21 ctx := context.Background()
    22 opts := options.Client().
    23 SetTimeout(5 * time.Second).
    24 ApplyURI("<connection-string>")
    25
    26 client, err := mongo.Connect(opts)
    27 if err != nil {
    28 panic(err)
    29 }
    30 defer client.Disconnect(ctx)
    31 // set namespace
    32 collection := client.Database("sample_mflix").Collection("movies")
    33 // define pipeline
    34 searchStage := bson.D{{"$search", bson.M{
    35 "index": "default",
    36 "compound": bson.M{
    37 "must": bson.M{
    38 "range": bson.M{
    39 "path": "year", "gte": 2013, "lte": 2015,
    40 },
    41 },
    42 "should": bson.D{
    43 {"text", bson.M{
    44 "path": "title", "query": "snow", "score": bson.M{
    45 "boost": bson.D{{"value", 2}},
    46 },
    47 }},
    48 },
    49 },
    50 }}}
    51 limitStage := bson.D{{"$limit", 10}}
    52 projectStage := bson.D{{"$project", bson.D{{"title", 1}, {"year", 1}, {"_id", 0}, {"score", bson.D{{"$meta", "searchScore"}}}}}}
    53 // run pipeline
    54 cursor, err := collection.Aggregate(ctx, mongo.Pipeline{searchStage, limitStage, projectStage})
    55 if err != nil {
    56 panic(err)
    57 }
    58 // print results
    59 var results []bson.D
    60 if err = cursor.All(context.TODO(), &results); err != nil {
    61 panic(err)
    62 }
    63 for _, result := range results {
    64 fmt.Println(result)
    65 }
    66}
  3. 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.

  4. Run the following command to query your collection:

    go run compound-boost-query.go
    [{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.

3
  1. Create a file named compound-boost-query.go.

  2. Copy and paste the code example into the compound-function-query.go file.

    The code example performs the following tasks:

    • Imports mongodb packages and dependencies.

    • Establishes a connection to your cluster.

    • Uses the following compound operator clauses:

      • must clause with the range operator to search for movies between the years 2013 to 2015.

      • should clause with the text operator to query for the term snow in the title field and alter the score with the function option. The function option 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.rating or the number 2 for those documents that do not have the imdb.rating field.

    • Specifies the highlight option to return snippets of text from the title field that match the query. The snippets contain matching text specified with type: 'hit', and adjacent text specified with type: 'text'.

    • Uses the following pipeline stages:

      • $limit stage to limit the output to 10 results

      • $project stage to:

        • Exclude all fields except title and year

        • Add two fields named score and highlights

    • Iterates over the cursor to print the documents that match the query.

    1package main
    2
    3import (
    4 "context"
    5 "fmt"
    6 "time"
    7
    8 "go.mongodb.org/mongo-driver/v2/bson"
    9 "go.mongodb.org/mongo-driver/v2/mongo"
    10 "go.mongodb.org/mongo-driver/v2/mongo/options"
    11)
    12
    13func main() {
    14 // connect to the Atlas cluster and set a maximum operation time
    15 opts := options.Client().
    16 SetTimeout(5 * time.Second).
    17 ApplyURI("<connection-string>")
    18
    19 client, err := mongo.Connect(opts)
    20 if err != nil {
    21 panic(err)
    22 }
    23 defer client.Disconnect(context.TODO())
    24
    25 // set namespace
    26 collection := client.Database("sample_mflix").Collection("movies")
    27
    28 // define pipeline
    29 searchStage := bson.D{{"$search", bson.M{
    30 "index": "default",
    31 "compound": bson.M{
    32 "must": bson.M{
    33 "range": bson.M{
    34 "path": "year", "gte": 2013, "lte": 2015,
    35 },
    36 },
    37 "should": bson.D{
    38 {"text", bson.M{
    39 "path": "title", "query": "snow", "score": bson.M{
    40 "function": bson.D{{"add", bson.A{
    41 bson.D{{"path", bson.D{
    42 {"value", "imdb.rating"}, {"undefined", 2},
    43 }}},
    44 bson.D{{"score", "relevance"}},
    45 }}},
    46 }}}},
    47 },
    48 "highlight": bson.D{{"path", "title"}},
    49 }}}
    50 limitStage := bson.D{{"$limit", 10}}
    51 projectStage := bson.D{{"$project", bson.D{{"title", 1}, {"year", 1}, {"_id", 0}, {"score", bson.D{{"$meta", "searchScore"}}}, {"highlights", bson.D{{"$meta", "searchHighlights"}}}}}}
    52
    53 // run pipeline
    54 cursor, err := collection.Aggregate(context.TODO(), mongo.Pipeline{searchStage, limitStage, projectStage})
    55 if err != nil {
    56 panic(err)
    57 }
    58
    59 // print results
    60 var results []bson.D
    61 if err = cursor.All(context.TODO(), &results); err != nil {
    62 panic(err)
    63 }
    64 for _, result := range results {
    65 fmt.Println(result)
    66 }
    67}
  3. 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.

  4. Run the following command to query your collection:

    go run compound-function-query.go
    [{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

junit

4.11 or higher version

mongodb-driver-sync

4.3.0 or higher version

slf4j-log4j12

1.7.30 or higher version

2
  1. Create a file named CompoundConstantQuery.java.

  2. Copy and paste the following code into the file.

    The code example performs the following tasks:

    • Imports mongodb packages and dependencies.

    • Establishes a connection to your cluster.

    • Uses the following compound clauses to query the collection:

      • filter clause with the range operator to search for movies between the years 2013 to 2015.

      • should clause with the text operator to query for the term snow in the title field and alter the score with the constant option. The constant option replaces all score results for the search term with 5.

    • Specifies the highlight option to return snippets of text from the title field that match the query. The snippets contain matching text specified with type: 'hit', and adjacent text specified with type: 'text'.

    • Uses the following pipeline stages:

      • $limit stage to limit the output to 10 results

      • $project stage to:

        • Exclude all fields except title and year

        • Add two fields named score and highlights

    • Iterates over the cursor to print the documents that match the query.

    1import java.util.Arrays;
    2import java.util.List;
    3
    4import static com.mongodb.client.model.Aggregates.limit;
    5import static com.mongodb.client.model.Aggregates.project;
    6import static com.mongodb.client.model.Projections.*;
    7import com.mongodb.client.MongoClient;
    8import com.mongodb.client.MongoClients;
    9import com.mongodb.client.MongoCollection;
    10import com.mongodb.client.MongoDatabase;
    11
    12import org.bson.Document;
    13
    14public class CompoundConstantQuery {
    15 public static void main( String[] args ) {
    16 // define clauses
    17 List<Document> mustClauses =
    18 List.of(
    19 new Document(
    20 "range", new Document("path", "year")
    21 .append("gte", 2013)
    22 .append("lte", 2015)));
    23 List<Document> shouldClauses =
    24 List.of(
    25 new Document("text",
    26 new Document("query", "snow")
    27 .append("path", "title")
    28 .append("score", new Document("constant", new Document("value", 5)))));
    29 Document highlightOption = new Document("path", "title");
    30 // define query
    31 Document agg =
    32 new Document("$search",
    33 new Document("index", "default")
    34 .append("compound",
    35 new Document("must", mustClauses).append("should", shouldClauses))
    36 .append("highlight", highlightOption));
    37 // specify connection
    38 String uri = "<connection-string>";
    39 // establish connection and set namespace
    40 try (MongoClient mongoClient = MongoClients.create(uri)) {
    41 MongoDatabase database = mongoClient.getDatabase("sample_mflix");
    42 MongoCollection<Document> collection = database.getCollection("movies");
    43 // run query and print results
    44 collection.aggregate(Arrays.asList(agg,
    45 limit(10),
    46 project(fields(
    47 excludeId(),
    48 include("title", "year"),
    49 computed("score", new Document("$meta", "searchScore")),
    50 computed("highlights", new Document("$meta", "searchHighlights"))))))
    51 .forEach(doc -> System.out.println(doc.toJson()));
    52 }
    53 }
    54}

    Note

    To run the sample code in your Maven environment, add the following above the import statements in your file.

    package com.mongodb.drivers;
  3. 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.

  4. Compile and run CompoundConstantQuery.java file.

    javac CompoundConstantQuery.java
    java CompoundConstantQuery
    {"title": "Snow in Paradise", "year": 2014, "score": 5.0, "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.0, "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.0, "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.0, "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.0, "highlights": []}
    {"title": "Jurassic World", "year": 2015, "score": 0.0, "highlights": []}
    {"title": "Action Jackson", "year": 2014, "score": 0.0, "highlights": []}
    {"year": 2013, "title": "In Secret", "score": 0.0, "highlights": []}
    {"title": "The Stanford Prison Experiment", "year": 2015, "score": 0.0, "highlights": []}
    {"year": 2014, "title": "The Giver", "score": 0.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.

3
  1. Create a file named CompoundBoostQuery.java.

  2. Copy and paste the following code into the file.

    The code example performs the following tasks:

    • Imports mongodb packages and dependencies.

    • Establishes a connection to your cluster.

    • Iterates over the cursor to print the documents that match the query.

    The query uses the following pipeline stages:

    • $search stage to query the collection. The query:

      • Uses the following compound operator clauses:

        • must clause with the range operator to search for movies between the years 2013 to 2015.

        • should clause with the text operator to query for the term snow in the title field and alter the score with the boost option. The boost option multiplies the base score in the results for the search term by 2.

      Specifies the highlight option to return snippets of text from the title field that match the query. The snippets contain matching text specified with type: 'hit', and adjacent text specified with type: 'text'.

    • $limit stage to limit the output to 10 results

    • $project stage to:

      • Exclude all fields except title and year

      • Add two fields named score and highlights

    1import java.util.Arrays;
    2import java.util.List;
    3
    4import static com.mongodb.client.model.Aggregates.limit;
    5import static com.mongodb.client.model.Aggregates.project;
    6import static com.mongodb.client.model.Projections.*;
    7import com.mongodb.client.MongoClient;
    8import com.mongodb.client.MongoClients;
    9import com.mongodb.client.MongoCollection;
    10import com.mongodb.client.MongoDatabase;
    11import org.bson.Document;
    12
    13public class CompoundBoostQuery {
    14 public static void main( String[] args ) {
    15 // define clauses
    16 List<Document> mustClauses =
    17 List.of(
    18 new Document(
    19 "range", new Document("path", "year")
    20 .append("gte", 2013)
    21 .append("lte", 2015)));
    22 List<Document> shouldClauses =
    23 List.of(
    24 new Document(
    25 "text",
    26 new Document("query", "snow")
    27 .append("path", "title")
    28 .append("score", new Document("boost", new Document("value", 2)))));
    29 Document highlightOption = new Document("path", "title");
    30 // define query
    31 Document agg =
    32 new Document("$search",
    33 new Document("index", "default")
    34 .append("compound",
    35 new Document("must", mustClauses).append("should", shouldClauses))
    36 .append("highlight", highlightOption));
    37 // specify connection
    38 String uri = "<connection-string>";
    39 // establish connection and set namespace
    40 try (MongoClient mongoClient = MongoClients.create(uri)) {
    41 MongoDatabase database = mongoClient.getDatabase("sample_mflix");
    42 MongoCollection<Document> collection = database.getCollection("movies");
    43 // run query and print results
    44 collection.aggregate(Arrays.asList(agg,
    45 limit(10),
    46 project(fields(
    47 excludeId(),
    48 include("title", "year"),
    49 computed("score", new Document("$meta", "searchScore")),
    50 computed("highlights", new Document("$meta", "searchHighlights"))))))
    51 .forEach(doc -> System.out.println(doc.toJson()));
    52 }
    53 }
    54}

    Note

    To run the sample code in your Maven environment, add the following above the import statements in your file.

    package com.mongodb.drivers;
  3. 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.

  4. Compile and run CompoundBoostQuery.java file.

    javac CompoundBoostQuery.java
    java CompoundBoostQuery
    {"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.0, "highlights": []}
    {"title": "Jurassic World", "year": 2015, "score": 1.0, "highlights": []}
    {"title": "Action Jackson", "year": 2014, "score": 1.0, "highlights": []}
    {"year": 2013, "title": "In Secret", "score": 1.0, "highlights": []}
    {"title": "The Stanford Prison Experiment", "year": 2015, "score": 1.0, "highlights": []}
    {"year": 2014, "title": "The Giver", "score": 1.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 boost option.

4
  1. Create a file named CompoundFunctionQuery.java.

  2. Copy and paste the following code into the file.

    The code example performs the following tasks:

    • Imports mongodb packages and dependencies.

    • Establishes a connection to your cluster.

    • Uses the following pipeline stages to query the collection:

      • must clause with the range operator to search for movies between the years 2013 to 2015.

      • should clause with the text operator to query for the term snow in the title field and alter the score with the function option. The function option 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.rating or the number 2 for those documents that do not have the imdb.rating field.

    • Uses the following pipeline stages:

      • $limit stage to limit the output to 10 results

      • $project stage to:

        • Exclude all fields except title and year

        • Add two fields named score and highlights

    • Specifies the highlight option to return snippets of text from the title field that match the query. The snippets contain matching text specified with type: 'hit', and adjacent text specified with type: 'text'.

    • Iterates over the cursor to print the documents that match the query.

    1import java.util.Arrays;
    2import java.util.List;
    3
    4import static com.mongodb.client.model.Aggregates.limit;
    5import static com.mongodb.client.model.Aggregates.project;
    6import static com.mongodb.client.model.Projections.*;
    7import com.mongodb.client.MongoClient;
    8import com.mongodb.client.MongoClients;
    9import com.mongodb.client.MongoCollection;
    10import com.mongodb.client.MongoDatabase;
    11import org.bson.Document;
    12
    13public class CompoundFunctionQuery {
    14 public static void main( String[] args ) {
    15 // define clauses
    16 List<Document> mustClauses =
    17 List.of(
    18 new Document("range", new Document("path", "year")
    19 .append("gte", 2013)
    20 .append("lte", 2015)));
    21 List<Document> shouldClauses =
    22 List.of(
    23 new Document("text",
    24 new Document("query", "snow")
    25 .append("path", "title")
    26 .append("score", new Document("function",
    27 new Document("add", Arrays.asList(
    28 new Document("path", new Document("value", "imdb.rating")
    29 .append("undefined", 2)), new Document("score", "relevance")))))));
    30 Document highlightOption = new Document("path", "title");
    31 // define query
    32 Document agg =
    33 new Document("$search",
    34 new Document("index", "default")
    35 .append("compound",
    36 new Document("must", mustClauses).append("should", shouldClauses))
    37 .append("highlight", highlightOption));
    38 // specify connection
    39 String uri = "<connection-string>";
    40 // establish connection and set namespace
    41 try (MongoClient mongoClient = MongoClients.create(uri)) {
    42 MongoDatabase database = mongoClient.getDatabase("sample_mflix");
    43 MongoCollection<Document> collection = database.getCollection("movies");
    44 // run query and print results
    45 collection.aggregate(Arrays.asList(agg,
    46 limit(10),
    47 project(fields(
    48 excludeId(),
    49 include("title", "year"),
    50 computed("score", new Document("$meta", "searchScore")),
    51 computed("highlights", new Document("$meta", "searchHighlights"))))))
    52 .forEach(doc -> System.out.println(doc.toJson()));
    53 }
    54 }
    55}

    Note

    To run the sample code in your Maven environment, add the following above the import statements in your file.

    package com.mongodb.drivers;
  3. 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.

  4. Compile and run CompoundFunctionQuery.java file.

    javac CompoundFunctionQuery.java
    java CompoundFunctionQuery
    {"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.0, "highlights": []}
    {"title": "Jurassic World", "year": 2015, "score": 1.0, "highlights": []}
    {"title": "Action Jackson", "year": 2014, "score": 1.0, "highlights": []}
    {"year": 2013, "title": "In Secret", "score": 1.0, "highlights": []}
    {"title": "The Stanford Prison Experiment", "year": 2015, "score": 1.0, "highlights": []}
    {"year": 2014, "title": "The Giver", "score": 1.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 function option.

1

mongodb-driver-kotlin-coroutine

4.10.0 or higher version

2
  1. Create a file named CompoundConstantQuery.kt.

  2. Copy and paste the following code into the file.

    The code example performs the following tasks:

    • Imports mongodb packages and dependencies.

    • Establishes a connection to your cluster.

    • Uses the following compound clauses to query the collection:

      • filter clause with the range operator to search for movies between the years 2013 to 2015.

      • should clause with the text operator to query for the term snow in the title field and alter the score with the constant option. The constant option replaces all score results for the search term with 5.

    • Specifies the highlight option to return snippets of text from the title field that match the query. The snippets contain matching text specified with type: 'hit', and adjacent text specified with type: 'text'.

    • Uses the following pipeline stages:

      • $limit stage to limit the output to 10 results

      • $project stage to:

        • Exclude all fields except title and year

        • Add two fields named score and highlights

    • Prints the documents that match the query from the AggregateFlow instance.

    1import com.mongodb.client.model.Aggregates.limit
    2import com.mongodb.client.model.Aggregates.project
    3import com.mongodb.client.model.Projections.*
    4import com.mongodb.kotlin.client.coroutine.MongoClient
    5import kotlinx.coroutines.runBlocking
    6import org.bson.Document
    7
    8fun main() {
    9 // establish connection and set namespace
    10 val uri = "<connection-string>"
    11 val mongoClient = MongoClient.create(uri)
    12 val database = mongoClient.getDatabase("sample_mflix")
    13 val collection = database.getCollection<Document>("movies")
    14
    15 runBlocking {
    16 // define clauses
    17 val mustClauses = listOf(
    18 Document(
    19 "range", Document("path", "year")
    20 .append("gte", 2013)
    21 .append("lte", 2015)
    22 )
    23 )
    24
    25 val shouldClauses = listOf(
    26 Document(
    27 "text",
    28 Document("query", "snow")
    29 .append("path", "title")
    30 .append("score", Document("constant", Document("value", 5)))
    31 )
    32 )
    33
    34 val highlightOption = Document("path", "title")
    35
    36 // define pipeline
    37 val agg = Document(
    38 "\$search",
    39 Document("index", "default")
    40 .append(
    41 "compound",
    42 Document("must", mustClauses).append("should", shouldClauses)
    43 )
    44 .append("highlight", highlightOption)
    45 )
    46
    47 val resultsFlow = collection.aggregate<Document>(
    48 listOf(
    49 agg,
    50 limit(10),
    51 project(fields(
    52 excludeId(),
    53 include("title", "year"),
    54 computed("score", Document("\$meta", "searchScore")),
    55 computed("highlights", Document("\$meta", "searchHighlights"))
    56 ))
    57 )
    58 )
    59 resultsFlow.collect { println(it) }
    60 }
    61 mongoClient.close()
    62}
  3. 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.

  4. Run the CompoundConstantQuery.kt file.

    When you run the CompoundConstantQuery.kt program in your IDE, it prints the following documents:

    Document{{title=Snow in Paradise, year=2014, score=6.0, highlights=[Document{{score=1.382846713066101, path=title, texts=[Document{{value=Snow, type=hit}}, Document{{value= in Paradise, type=text}}]}}]}}
    Document{{title=Dead Snow 2: Red vs. Dead, year=2014, score=6.0, highlights=[Document{{score=1.3924485445022583, path=title, texts=[Document{{value=Dead , type=text}}, Document{{value=Snow, type=hit}}, Document{{value= 2: Red vs. , type=text}}]}}]}}
    Document{{title=The Snow White Murder Case, year=2014, score=6.0, highlights=[Document{{score=1.3525336980819702, path=title, texts=[Document{{value=The , type=text}}, Document{{value=Snow, type=hit}}, Document{{value= White Murder Case, type=text}}]}}]}}
    Document{{title=Snow on the Blades, year=2014, score=6.0, highlights=[Document{{score=1.3766303062438965, path=title, texts=[Document{{value=Snow, type=hit}}, Document{{value= on the Blades, type=text}}]}}]}}
    Document{{year=2013, title=The Secret Life of Walter Mitty, score=1.0, highlights=[]}}
    Document{{title=Jurassic World, year=2015, score=1.0, highlights=[]}}
    Document{{title=Action Jackson, year=2014, score=1.0, highlights=[]}}
    Document{{year=2013, title=In Secret, score=1.0, highlights=[]}}
    Document{{title=The Stanford Prison Experiment, year=2015, score=1.0, highlights=[]}}
    Document{{year=2014, title=The Giver, score=1.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.

3
  1. Create a file named CompoundBoostQuery.kt.

  2. Copy and paste the following code into the file.

    The code example performs the following tasks:

    • Imports mongodb packages and dependencies.

    • Establishes a connection to your cluster.

    • Prints the documents that match the query from the AggregateFlow instance.

    The query uses the following pipeline stages:

    • $search stage to query the collection. The query:

      • Uses the following compound operator clauses:

        • must clause with the range operator to search for movies between the years 2013 to 2015.

        • should clause with the text operator to query for the term snow in the title field and alter the score with the boost option. The boost option multiplies the base score in the results for the search term by 2.

      Specifies the highlight option to return snippets of text from the title field that match the query. The snippets contain matching text specified with type: 'hit', and adjacent text specified with type: 'text'.

    • $limit stage to limit the output to 10 results

    • $project stage to:

      • Exclude all fields except title and year

      • Add two fields named score and highlights

    1import com.mongodb.client.model.Aggregates.limit
    2import com.mongodb.client.model.Aggregates.project
    3import com.mongodb.client.model.Projections.*
    4import com.mongodb.kotlin.client.coroutine.MongoClient
    5import kotlinx.coroutines.runBlocking
    6import org.bson.Document
    7
    8fun main() {
    9 // establish connection and set namespace
    10 val uri = "<connection-string>"
    11 val mongoClient = MongoClient.create(uri)
    12
    13 val database = mongoClient.getDatabase("sample_mflix")
    14 val collection = database.getCollection<Document>("movies")
    15
    16 runBlocking {
    17 // define clauses
    18 val mustClauses = listOf(
    19 Document(
    20 "range", Document("path", "year")
    21 .append("gte", 2013)
    22 .append("lte", 2015)
    23 )
    24 )
    25
    26 val shouldClauses = listOf(
    27 Document(
    28 "text",
    29 Document("query", "snow")
    30 .append("path", "title")
    31 .append("score", Document("boost", Document("value", 2)))
    32 )
    33 )
    34
    35 val highlightOption = Document("path", "title")
    36
    37 // define pipeline
    38 val agg = Document(
    39 "\$search",
    40 Document("index", "default")
    41 .append(
    42 "compound",
    43 Document("must", mustClauses).append("should", shouldClauses)
    44 )
    45 .append("highlight", highlightOption)
    46 )
    47
    48 // run query and print results
    49 val resultsFlow = collection.aggregate<Document>(
    50 listOf(
    51 agg,
    52 limit(10),
    53 project(fields(
    54 excludeId(),
    55 include("title", "year"),
    56 computed("score", Document("\$meta", "searchScore")),
    57 computed("highlights", Document("\$meta", "searchHighlights"))
    58 ))
    59 )
    60 )
    61 resultsFlow.collect { println(it) }
    62 }
    63 mongoClient.close()
    64}
  3. 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.

  4. Run the CompoundBoostQuery.kt file.

    When you run the CompoundBoostQuery.kt program in your IDE, it prints the following documents:

    Document{{title=Snow in Paradise, year=2014, score=6.784297466278076, highlights=[Document{{score=1.382846713066101, path=title, texts=[Document{{value=Snow, type=hit}}, Document{{value= in Paradise, type=text}}]}}]}}
    Document{{title=Snow on the Blades, year=2014, score=6.073266506195068, highlights=[Document{{score=1.3766303062438965, path=title, texts=[Document{{value=Snow, type=hit}}, Document{{value= on the Blades, type=text}}]}}]}}
    Document{{title=The Snow White Murder Case, year=2014, score=5.517906188964844, highlights=[Document{{score=1.3525336980819702, path=title, texts=[Document{{value=The , type=text}}, Document{{value=Snow, type=hit}}, Document{{value= White Murder Case, type=text}}]}}]}}
    Document{{title=Dead Snow 2: Red vs. Dead, year=2014, score=5.072136878967285, highlights=[Document{{score=1.3924485445022583, path=title, texts=[Document{{value=Dead , type=text}}, Document{{value=Snow, type=hit}}, Document{{value= 2: Red vs. , type=text}}]}}]}}
    Document{{year=2013, title=The Secret Life of Walter Mitty, score=1.0, highlights=[]}}
    Document{{title=Jurassic World, year=2015, score=1.0, highlights=[]}}
    Document{{title=Action Jackson, year=2014, score=1.0, highlights=[]}}
    Document{{year=2013, title=In Secret, score=1.0, highlights=[]}}
    Document{{title=The Stanford Prison Experiment, year=2015, score=1.0, highlights=[]}}
    Document{{year=2014, title=The Giver, score=1.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 boost option.

4
  1. Create a file named CompoundFunctionQuery.kt.

  2. Copy and paste the following code into the file.

    The code example performs the following tasks:

    • Imports mongodb packages and dependencies.

    • Establishes a connection to your cluster.

    • Uses the following pipeline stages to query the collection:

      • must clause with the range operator to search for movies between the years 2013 to 2015.

      • should clause with the text operator to query for the term snow in the title field and alter the score with the function option. The function option 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.rating or the number 2 for those documents that do not have the imdb.rating field.

    • Uses the following pipeline stages:

      • $limit stage to limit the output to 10 results

      • $project stage to:

        • Exclude all fields except title and year

        • Add two fields named score and highlights

    • Specifies the highlight option to return snippets of text from the title field that match the query. The snippets contain matching text specified with type: 'hit', and adjacent text specified with type: 'text'.

    • Prints the documents that match the query from the AggregateFlow instance.

    1import com.mongodb.client.model.Aggregates.limit
    2import com.mongodb.client.model.Aggregates.project
    3import com.mongodb.client.model.Projections.*
    4import com.mongodb.kotlin.client.coroutine.MongoClient
    5import kotlinx.coroutines.runBlocking
    6import org.bson.Document
    7
    8fun main() {
    9 // establish connection and set namespace
    10 val uri = "<connection-string>"
    11 val mongoClient = MongoClient.create(uri)
    12
    13 val database = mongoClient.getDatabase("sample_mflix")
    14 val collection = database.getCollection<Document>("movies")
    15
    16 runBlocking {
    17 // define clauses
    18 val mustClauses = listOf(
    19 Document(
    20 "range", Document("path", "year")
    21 .append("gte", 2013)
    22 .append("lte", 2015)
    23 )
    24 )
    25
    26 val shouldClauses = listOf(
    27 Document("text", Document("query", "snow")
    28 .append("path", "title")
    29 .append("score",
    30 Document("function", Document("add", listOf(
    31 Document("path", Document("value", "imdb.rating").append("undefined", 2)),
    32 Document("score", "relevance")
    33 )))
    34 )
    35 )
    36 )
    37
    38 val highlightOption = Document("path", "title")
    39
    40 // define pipeline
    41 val agg = Document(
    42 "\$search",
    43 Document("index", "default")
    44 .append(
    45 "compound",
    46 Document("must", mustClauses).append("should", shouldClauses)
    47 )
    48 .append("highlight", highlightOption)
    49 )
    50
    51 // run query and print results
    52 val resultsFlow = collection.aggregate<Document>(
    53 listOf(
    54 agg,
    55 limit(10),
    56 project(fields(
    57 excludeId(),
    58 include("title", "year"),
    59 computed("score", Document("\$meta", "searchScore")),
    60 computed("highlights", Document("\$meta", "searchHighlights"))
    61 ))
    62 )
    63 )
    64 resultsFlow.collect { println(it) }
    65 }
    66 mongoClient.close()
    67}
  3. 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.

  4. Run the CompoundFunctionQuery.kt file.

    When you run the CompoundFunctionQuery.kt program in your IDE, it prints the following documents:

    Document{{title=The Snow White Murder Case, year=2014, score=10.458952903747559, highlights=[Document{{score=1.3525336980819702, path=title, texts=[Document{{value=The , type=text}}, Document{{value=Snow, type=hit}}, Document{{value= White Murder Case, type=text}}]}}]}}
    Document{{title=Snow on the Blades, year=2014, score=10.336633682250977, highlights=[Document{{score=1.3766303062438965, path=title, texts=[Document{{value=Snow, type=hit}}, Document{{value= on the Blades, type=text}}]}}]}}
    Document{{title=Dead Snow 2: Red vs. Dead, year=2014, score=10.036067962646484, highlights=[Document{{score=1.3924485445022583, path=title, texts=[Document{{value=Dead , type=text}}, Document{{value=Snow, type=hit}}, Document{{value= 2: Red vs. , type=text}}]}}]}}
    Document{{title=Snow in Paradise, year=2014, score=8.392148971557617, highlights=[Document{{score=1.382846713066101, path=title, texts=[Document{{value=Snow, type=hit}}, Document{{value= in Paradise, type=text}}]}}]}}
    Document{{year=2013, title=The Secret Life of Walter Mitty, score=1.0, highlights=[]}}
    Document{{title=Jurassic World, year=2015, score=1.0, highlights=[]}}
    Document{{title=Action Jackson, year=2014, score=1.0, highlights=[]}}
    Document{{year=2013, title=In Secret, score=1.0, highlights=[]}}
    Document{{title=The Stanford Prison Experiment, year=2015, score=1.0, highlights=[]}}
    Document{{year=2014, title=The Giver, score=1.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 function option.

1
  1. Create a file named compound-constant-query.js.

  2. Copy and paste the code example into the compound-constant-query.js file.

    The code example performs the following tasks:

    • Imports mongodb, MongoDB's Node.js driver.

    • Creates an instance of the MongoClient class to establish a connection to your cluster.

    • Uses the following compound clauses to query the collection:

      • filter clause with the range operator to search for movies between the years 2013 to 2015.

      • should clause with the text operator to query for the term snow in the title field and alter the score with the constant option. The constant option replaces all score results for the search term with 5.

    • Specifies the highlight option to return snippets of text from the title field that match the query. The snippets contain matching text specified with type: 'hit', and adjacent text specified with type: 'text'.

    • Uses the following pipeline stages:

      • $limit stage to limit the output to 10 results

      • $project stage to:

        • Exclude all fields except title and year

        • Add two fields named score and highlights

    • Iterates over the cursor to print the documents that match the query.

    1const MongoClient = require("mongodb").MongoClient;
    2const assert = require("assert");
    3
    4const agg = [
    5 {
    6 '$search': {
    7 'index': 'default',
    8 'compound': {
    9 'filter': [
    10 {
    11 'range': {
    12 'path': 'year',
    13 'gte': 2013,
    14 'lte': 2015
    15 }
    16 }
    17 ],
    18 'should': [
    19 {
    20 'text': {
    21 'query': 'snow',
    22 'path': 'title',
    23 'score': {
    24 'constant': {
    25 'value': 5
    26 }
    27 }
    28 }
    29 }
    30 ]
    31 },
    32 'highlight': {
    33 'path': 'title'
    34 }
    35 }
    36 }, {
    37 '$limit': 10
    38 }, {
    39 '$project': {
    40 '_id': 0,
    41 'title': 1,
    42 'year': 1,
    43 'score': {
    44 '$meta': 'searchScore'
    45 },
    46 'highlights': {
    47 '$meta': 'searchHighlights'
    48 }
    49 }
    50 }
    51];
    52
    53MongoClient.connect(
    54 "<connection-string>",
    55 async function (connectErr, client) {
    56 assert.equal(null, connectErr);
    57 const coll = client.db("sample_mflix").collection("movies");
    58 let cursor = await coll.aggregate(agg);
    59 await cursor.forEach((doc) => console.log(doc));
    60 client.close();
    61 }
    62);
  3. 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.

  4. Run the following command to query your collection:

    node compound-constant-query.js
    '{"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.

2
  1. Create a file named compound-boost-query.js.

  2. Copy and paste the code example into the compound-boost-query.js file.

    The code example performs the following tasks:

    • Imports mongodb, MongoDB's Node.js driver.

    • Creates an instance of the MongoClient class to establish a connection to your cluster.

    • Iterates over the cursor to print the documents that match the query.

    The query uses the following pipeline stages:

    • $search stage to query the collection. The query:

      • Uses the following compound operator clauses:

        • must clause with the range operator to search for movies between the years 2013 to 2015.

        • should clause with the text operator to query for the term snow in the title field and alter the score with the boost option. The boost option multiplies the base score in the results for the search term by 2.

      • Specifies the highlight option to return snippets of text from the title field that match the query. The snippets contain matching text specified with type: 'hit', and adjacent text specified with type: 'text'.

    • $limit stage to limit the output to 10 results

    • $project stage to:

      • Exclude all fields except title and year

      • Add two fields named score and highlights

    1const MongoClient = require("mongodb").MongoClient;
    2const assert = require("assert");
    3
    4const agg = [
    5 {
    6 '$search': {
    7 'index': 'default',
    8 'compound': {
    9 'must': [
    10 {
    11 'range': {
    12 'path': 'year',
    13 'gte': 2013,
    14 'lte': 2015
    15 }
    16 }
    17 ],
    18 'should': [
    19 {
    20 'text': {
    21 'query': 'snow',
    22 'path': 'title',
    23 'score': {
    24 'boost': {
    25 'value': 2
    26 }
    27 }
    28 }
    29 }
    30 ]
    31 }
    32 }
    33 }, {
    34 '$limit': 10
    35 }, {
    36 '$project': {
    37 '_id': 0,
    38 'title': 1,
    39 'year': 1,
    40 'score': {
    41 '$meta': 'searchScore'
    42 }
    43 }
    44 }
    45];
    46
    47MongoClient.connect(
    48 "<connection-string>",
    49 async function (connectErr, client) {
    50 assert.equal(null, connectErr);
    51 const coll = client.db("sample_mflix").collection("movies");
    52 let cursor = await coll.aggregate(agg);
    53 await cursor.forEach((doc) => console.log(doc));
    54 client.close();
    55 }
    56);
  3. 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.

  4. Run the following command to query your collection:

    node compound-boost-query.js
    '{"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.

3
  1. Create a file named compound-function-query.js.

  2. Copy and paste the code example into the compound-function-query.js file.

    The code example performs the following tasks:

    • Imports mongodb, MongoDB's Node.js driver.

    • Creates an instance of the MongoClient class to establish a connection to your cluster.

    • Uses the following compound clauses to query the collection:

      • must clause with the range operator to search for movies between the years 2013 to 2015.

      • should clause with the text operator to query for the term snow in the title field and alter the score with the function option. The function option 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.rating or the number 2 for those documents that do not have the imdb.rating field.

    • Specifies the highlight option to return snippets of text from the title field that match the query. The snippets contain matching text specified with type: 'hit', and adjacent text specified with type: 'text'.

    • Uses the following pipeline stages:

      • $limit stage to limit the output to 10 results

      • $project stage to:

        • Exclude all fields except title and year

        • Add two fields named score and highlights

    • Iterates over the cursor to print the documents that match the query.

    1const MongoClient = require("mongodb").MongoClient;
    2const assert = require("assert");
    3
    4const agg = [
    5 {
    6 '$search': {
    7 'index': 'default',
    8 'compound': {
    9 'must': [
    10 {
    11 'range': {
    12 'path': 'year',
    13 'gte': 2013,
    14 'lte': 2015
    15 }
    16 }
    17 ],
    18 'should': [
    19 {
    20 'text': {
    21 'query': 'snow',
    22 'path': 'title',
    23 'score': {
    24 'function': {
    25 'add': [
    26 {
    27 'path': {
    28 'value': 'imdb.rating',
    29 'undefined': 2
    30 }
    31 }, {
    32 'score': 'relevance'
    33 }
    34 ]
    35 }
    36 }
    37 }
    38 }
    39 ]
    40 }
    41 }
    42 }, {
    43 '$limit': 10
    44 }, {
    45 '$project': {
    46 '_id': 0,
    47 'title': 1,
    48 'year': 1,
    49 'score': {
    50 '$meta': 'searchScore'
    51 },
    52 'highlights': {
    53 '$meta': 'searchHighlights'
    54 }
    55 }
    56 }
    57];
    58
    59MongoClient.connect(
    60 "<connection-string>",
    61 async function (connectErr, client) {
    62 assert.equal(null, connectErr);
    63 const coll = client.db("sample_mflix").collection("movies");
    64 let cursor = await coll.aggregate(agg);
    65 await cursor.forEach((doc) => console.log(doc));
    66 client.close();
    67 }
    68);
  3. 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.

  4. Run the following command to query your collection:

    node compound-function-query.js
    '{"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
  1. Create a file named compound-constant-query.py.

  2. Copy and paste the code example into the compound-constant.py file.

    The following code example:

    • Imports pymongo, MongoDB's Python driver, and the dns module, which is required to connect pymongo to Atlas using a DNS seed list connection string.

    • Creates an instance of the MongoClient class to establish a connection to your cluster.

    • Uses the following compound clauses to query the collection:

      • filter clause with the range operator to search for movies between the years 2013 to 2015.

      • should clause with the text operator to query for the term snow in the title field and alter the score with the constant option. The constant option replaces all score results for the search term with 5.

    • Specifies the highlight option to return snippets of text from the title field that match the query. The snippets contain matching text specified with type: 'hit', and adjacent text specified with type: 'text'.

    • Uses the following pipeline stages:

      • $limit stage to limit the output to 10 results

      • $project stage to:

        • Exclude all fields except title and year

        • Add two fields named score and highlights

    • Iterates over the cursor to print the documents that match the query.

    1import pymongo
    2
    3# connect to your Atlas cluster
    4client = pymongo.MongoClient('<connection-string>')
    5
    6# define pipeline
    7pipeline = [
    8 {'$search': {
    9 'index': 'default',
    10 'compound': {
    11 'filter': [{'range': {'path': 'year', 'gte': 2013, 'lte': 2015}}],
    12 'should': [{'text': {'query': 'snow', 'path': 'title', 'score': {'constant': {'value': 5}}}}]},
    13 'highlight': {'path': 'title'}}},
    14 {'$limit': 10},
    15 {'$project': {'_id': 0, 'title': 1, 'year': 1,
    16 'score': {'$meta': 'searchScore'}, "highlights": {"$meta": "searchHighlights"}}}
    17]
    18
    19# run pipeline
    20result = client['sample_mflix']['movies'].aggregate(pipeline)
    21
    22# print results
    23for i in result:
    24 print(i)
  3. 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.

  4. Run the following command to query your collection:

    python compound-constant-query.py
    {'highlights': [{'path': 'title', 'score': 1.382846713066101, 'texts': [{'type': 'hit', 'value': 'Snow'}, {'type': 'text', 'value': ' in Paradise'}]}], 'year': 2014, 'score': 5.0, 'title': 'Snow in Paradise'}
    {'highlights': [{'path': 'title', 'score': 1.3924485445022583, 'texts': [{'type': 'text', 'value': 'Dead '}, {'type': 'hit', 'value': 'Snow'}, {'type': 'text', 'value': ' 2: Red vs. '}]}], 'year': 2014, 'score': 5.0, 'title': 'Dead Snow 2: Red vs. Dead'}
    {'highlights': [{'path': 'title', 'score': 1.3525336980819702, 'texts': [{'type': 'text', 'value': 'The '}, {'type': 'hit', 'value': 'Snow'}, {'type': 'text', 'value': ' White Murder Case'}]}], 'year': 2014, 'score': 5.0, 'title': 'The Snow White Murder Case'}
    {'highlights': [{'path': 'title', 'score': 1.3766303062438965, 'texts': [{'type': 'hit', 'value': 'Snow'}, {'type': 'text', 'value': ' on the Blades'}]}], 'year': 2014, 'score': 5.0, 'title': 'Snow on the Blades'}
    {'highlights': [], 'title': 'The Secret Life of Walter Mitty', 'score': 0.0, 'year': 2013}
    {'highlights': [], 'year': 2015, 'score': 0.0, 'title': 'Jurassic World'}
    {'highlights': [], 'year': 2014, 'score': 0.0, 'title': 'Action Jackson'}
    {'highlights': [], 'title': 'In Secret', 'score': 0.0, 'year': 2013}
    {'highlights': [], 'year': 2015, 'score': 0.0, 'title': 'The Stanford Prison Experiment'}
    {'highlights': [], 'title': 'The Giver', 'score': 0.0, 'year': 2014}

    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 a MongoDB Search compound query that alters the score using the boost option. a. Create a file named compound-boost-query.py.

  1. Copy and paste the code example into the compound-boost-query.py file.

    The following code example:

    • Imports pymongo, MongoDB's Python driver, and the dns module, which is required to connect pymongo to Atlas using a DNS seed list connection string.

    • Creates an instance of the MongoClient class to establish a connection to your cluster.

    • Iterates over the cursor to print the documents that match the query.

    The query uses the following pipeline stages:

    • $search stage to query the collection. The query:

      • Uses the following compound operator clauses:

        • must clause with the range operator to search for movies between the years 2013 to 2015.

        • should clause with the text operator to query for the term snow in the title field and alter the score with the boost option. The boost option multiplies the base score in the results for the search term by 2.

        • Specifies the highlight option to return snippets of text from the title field that match the query. The snippets contain matching text specified with type: 'hit', and adjacent text specified with type: 'text'.
    • $limit stage to limit the output to 10 results

    • $project stage to:

      • Exclude all fields except title and year

      • Add two fields named score and highlights

    1import pymongo
    2
    3# connect to your Atlas cluster
    4client = pymongo.MongoClient('<connection-string>')
    5
    6# define pipeline
    7pipeline = [
    8 {'$search': {
    9 'index': 'default',
    10 'compound': {
    11 'must': [{'range': {'path': 'year', 'gte': 2013, 'lte': 2015}}],
    12 'should': [{'text': {'query': 'snow', 'path': 'title', 'score': {'boost': {'value': 2}}}}]},
    13 'highlight': {'path': 'title'}}},
    14 {'$limit': 10},
    15 {'$project': {'_id': 0, 'title': 1, 'year': 1, 'score': {'$meta': 'searchScore'}, "highlights": {"$meta": "searchHighlights"}}}
    16]
    17
    18# run pipeline
    19result = client['sample_mflix']['movies'].aggregate(pipeline)
    20
    21# print results
    22for i in result:
    23 print(i)
  2. 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.

  3. Run the following command to query your collection:

    python compound-boost-query.py
    {'highlights': [{'path': 'title', 'score': 1.382846713066101, 'texts': [{'type': 'hit', 'value': 'Snow'}, {'type': 'text', 'value': ' in Paradise'}]}], 'year': 2014, 'score': 6.7722930908203125, 'title': 'Snow in Paradise'}
    {'highlights': [{'path': 'title', 'score': 1.3766303062438965, 'texts': [{'type': 'hit', 'value': 'Snow'}, {'type': 'text', 'value': ' on the Blades'}]}], 'year': 2014, 'score': 6.063445568084717, 'title': 'Snow on the Blades'}
    {'highlights': [{'path': 'title', 'score': 1.3525336980819702, 'texts': [{'type': 'text', 'value': 'The '}, {'type': 'hit', 'value': 'Snow'}, {'type': 'text', 'value': ' White Murder Case'}]}], 'year': 2014, 'score': 5.509652137756348, 'title': 'The Snow White Murder Case'}
    {'highlights': [{'path': 'title', 'score': 1.3924485445022583, 'texts': [{'type': 'text', 'value': 'Dead '}, {'type': 'hit', 'value': 'Snow'}, {'type': 'text', 'value': ' 2: Red vs. '}]}], 'year': 2014, 'score': 5.065053939819336, 'title': 'Dead Snow 2: Red vs. Dead'}
    {'highlights': [], 'title': 'The Secret Life of Walter Mitty', 'score': 1.0, 'year': 2013}
    {'highlights': [], 'year': 2015, 'score': 1.0, 'title': 'Jurassic World'}
    {'highlights': [], 'year': 2014, 'score': 1.0, 'title': 'Action Jackson'}
    {'highlights': [], 'title': 'In Secret', 'score': 1.0, 'year': 2013}
    {'highlights': [], 'year': 2015, 'score': 1.0, 'title': 'The Stanford Prison Experiment'}
    {'highlights': [], 'title': 'The Giver', 'score': 1.0, 'year': 2014}

    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
  1. Create a file named compound-function-query.py.

  2. Copy and paste the code example into the compound-function-query.py file.

    The following code example:

    • Imports pymongo, MongoDB's Python driver, and the dns module, which is required to connect pymongo to Atlas using a DNS seed list connection string.

    • Creates an instance of the MongoClient class to establish a connection to your cluster.

    • Uses the following compound clauses to query the collection:

      • must clause with the range operator to search for movies between the years 2013 to 2015.

      • should clause with the text operator to query for the term snow in the title field and alter the score with the function option. The function option 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.rating or the number 2 for those documents that do not have the imdb.rating field.

    • Specifies the highlight option to return snippets of text from the title field that match the query. The snippets contain matching text specified with type: 'hit', and adjacent text specified with type: 'text'.

    • Uses the following pipeline stages:

      • $limit stage to limit the output to 10 results

      • $project stage to:

        • Exclude all fields except title and year

        • Add two fields named score and highlights

    • Iterates over the cursor to print the documents that match the query.

    1import pymongo
    2
    3# connect to your Atlas cluster
    4client = pymongo.MongoClient('<connection-string>')
    5
    6# define pipeline
    7pipeline = [
    8 {'$search': {
    9 'index': 'default',
    10 'compound': {
    11 'must': [{'range': {'path': 'year', 'gte': 2013, 'lte': 2015}}],
    12 'should': [{'text': {'query': 'snow', 'path': 'title',
    13 'score': {'function': {
    14 'add': [{'path': {'value': 'imdb.rating','undefined': 2}}, {'score': 'relevance'}]}}}}]},
    15 'highlight': {'path': 'title'}}},
    16 {'$limit': 10},
    17 {'$project': {'_id': 0, 'title': 1, 'year': 1, 'score': {'$meta': 'searchScore'}, "highlights": {"$meta": "searchHighlights"}}}
    18]
    19
    20# run pipeline
    21result = client['sample_mflix']['movies'].aggregate(pipeline)
    22
    23# print results
    24for i in result:
    25 print(i)
  3. 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.

  4. Run the following command to query your collection:

    python compound-function-query.py
    {'highlights': [{'path': 'title', 'score': 1.3525336980819702, 'texts': [{'type': 'text', 'value': 'The '}, {'type': 'hit', 'value': 'Snow'}, {'type': 'text', 'value': ' White Murder Case'}]}], 'year': 2014, 'score': 10.454826354980469, 'title': 'The Snow White Murder Case'}
    {'highlights': [{'path': 'title', 'score': 1.3766303062438965, 'texts': [{'type': 'hit', 'value': 'Snow'}, {'type': 'text', 'value': ' on the Blades'}]}], 'year': 2014, 'score': 10.3317232131958, 'title': 'Snow on the Blades'}
    {'highlights': [{'path': 'title', 'score': 1.3924485445022583, 'texts': [{'type': 'text', 'value': 'Dead '}, {'type': 'hit', 'value': 'Snow'}, {'type': 'text', 'value': ' 2: Red vs. '}]}], 'year': 2014, 'score': 10.032526969909668, 'title': 'Dead Snow 2: Red vs. Dead'}
    {'highlights': [{'path': 'title', 'score': 1.382846713066101, 'texts': [{'type': 'hit', 'value': 'Snow'}, {'type': 'text', 'value': ' in Paradise'}]}], 'year': 2014, 'score': 8.386146545410156, 'title': 'Snow in Paradise'}
    {'highlights': [], 'title': 'The Secret Life of Walter Mitty', 'score': 1.0, 'year': 2013}
    {'highlights': [], 'year': 2015, 'score': 1.0, 'title': 'Jurassic World'}
    {'highlights': [], 'year': 2014, 'score': 1.0, 'title': 'Action Jackson'}
    {'highlights': [], 'title': 'In Secret', 'score': 1.0, 'year': 2013}
    {'highlights': [], 'year': 2015, 'score': 1.0, 'title': 'The Stanford Prison Experiment'}
    {'highlights': [], 'title': 'The Giver', 'score': 1.0, 'year': 2014}

    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

You can go the MongoDB Search page from the Search & Vector Search option, or the Data Explorer.

  1. If it's not already displayed, select the organization that contains your project from the Organizations menu in the navigation bar.

  2. If it's not already displayed, select your project from the Projects menu in the navigation bar.

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

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

2

Click the Query button to the right of the index to query.

3

Click Edit Query to view a default query syntax sample in JSON format.

4
  1. Copy and paste the following query into the Query Editor.

    The query uses the $search compound operator should clause to nest compound operator queries that perform the following actions:

    • Searches for movies that contain the term ghost in the plot or title (must clause) and aren't in the comedy genre (mustNot clause).

    • Searches for movies that contain the term ghost in the plot or title (must clause), but reduces (boost) the score by 50% (0.5) for movies in the comedy genre with the term ghost in the title or plot.

    1[
    2 {
    3 "$search": {
    4 "index": "default",
    5 "compound": {
    6 "should":[ {
    7 "compound":{
    8 "must":[
    9 {
    10 "text": {
    11 "query": "ghost",
    12 "path": ["plot","title"]
    13 }
    14 }
    15 ],
    16 "mustNot":[
    17 {
    18 "text": {
    19 "query": "Comedy",
    20 "path": ["genres"]
    21 }
    22 }
    23 ]
    24 }
    25 },
    26 {
    27 "compound":{
    28 "must":[
    29 {
    30 "text": {
    31 "query": "ghost",
    32 "path": ["plot","title"]
    33 }
    34 }
    35 ],
    36 "filter":[
    37 {
    38 "text": {
    39 "query": "Comedy",
    40 "path": ["genres"]
    41 }
    42 }
    43 ],
    44 "score":{ "boost": { "value": 0.5} }
    45 }
    46 }
    47 ]
    48 }
    49 }
    50 }
    51]
  2. Click the Search button in the Query Editor.

    1SCORE: 5.909613132476807
    2_id: “573a139af29313caabcefcce”
    3plot: "Adaption of the famous Oscar Wilde tale about a young American girl th…"
    4genres: Array (3)
    5runtime: 92
    6
    7SCORE: 5.367666244506836
    8_id: “573a13d8f29313caabda5dc1”
    9plot: "The Little Ghost lives in the castle over looking a small town and awa…"
    10genres: Array (2)
    11runtime: 92
    12
    13SCORE: 4.676314353942871
    14_id: “573a13c0f29313caabd6139d”
    15plot: "Renowned "ghost hunter", Carter Simms is paid to conduct a paranormal …"
    16genres: Array (2)
    17runtime: 107
    18
    19SCORE: 3.9638845920562744
    20_id: “573a1398f29313caabcebf6f”
    21plot: "After an accident leaves a young man dead, his spirit stays behind to …"
    22genres: Array (3)
    23runtime: 127
    24
    25SCORE: 3.9638845920562744
    26_id: “573a13cdf29313caabd83c08”
    27plot: "A man tries to solve his lover's murder by communicating with her spir…"
    28genres: Array (3)
    29runtime: 115
    30
    31SCORE: 3.9638845920562744
    32_id: “573a13cef29313caabd873a2”
    33plot: "A man tries to solve his lover's murder by communicating with her spir…"
    34genres: Array (3)
    35runtime: 115
    36
    37SCORE: 3.526711940765381
    38_id: “573a13c3f29313caabd6a149”
    39plot: "What kind of scenes in a horror film scares you the most? When a ghost…"
    40genres: Array (2)
    41runtime: 95
    42
    43SCORE: 3.3177831172943115
    44_id: “573a1397f29313caabce7ea1”
    45plot: "Four successful elderly gentlemen, members of the Chowder Society, sha…"
    46genres: Array (3)
    47runtime: 110
    48
    49SCORE: 3.3177831172943115
    50_id: “573a13a4f29313caabd117df”
    51fullplot: "When the motorcyclist Johnny Blaze finds that his father Barton Blaze …"
    52imdb: Object
    53year: 2007
    54
    55SCORE: 3.3177831172943115
    56_id: “573a13a6f29313caabd185dc”
    57fullplot: "After discovering a passenger ship missing since 1962 floating adrift …"
    58imdb: Object
    59year: 2002

    The movie documents in the results contain the query term ghost in the plot or title field and aren't in the Comedy genre. MongoDB Search didn't return documents in the Comedy genre with the term ghost in the plot or title field because those documents didn't rank in the top 10 documents since the query reduced the score of those documents by 50%.

1

Open mongosh in a terminal window and connect to your cluster. For detailed instructions on connecting, see Connect to a Cluster via mongosh.

2
use sample_mflix
switched to db sample_mflix
3

This query uses the following pipeline stages:

  • Searches for movies that contain the term ghost in the plot or title (must clause) and aren't in the comedy genre (mustNot clause).

  • Searches for movies that contain the term ghost in the plot or title (must clause) and are in the comedy genre (filter clause), but reduces the score by 50% (boost).

Limits the number of results to 10 documents.

  • Includes only the _id, title, plot, and genres fields from the documents in the results.

  • Adds a field named score that shows the score in the results.

1db.movies.aggregate([
2 {
3 "$search": {
4 "index": "default",
5 "compound": {
6 "should": [
7 {
8 "compound":{
9 "must": [
10 {
11 "text": {
12 "query": "ghost",
13 "path": ["plot","title"]
14 }
15 }
16 ],
17 "mustNot": [
18 {
19 "text": {
20 "query": "Comedy",
21 "path": ["genres"]
22 }
23 }
24 ]
25 }
26 },
27 {
28 "compound":{
29 "must":[
30 {
31 "text": {
32 "query": "ghost",
33 "path": ["plot","title"]
34 }
35 }
36 ],
37 "filter": [
38 {
39 "text": {
40 "query": "Comedy",
41 "path": ["genres"]
42 }
43 }
44 ],
45 "score": { "boost": { "value": 0.5} }
46 }
47 }
48 ]
49 }
50 }
51 },
52 {
53 "$limit": 10
54 },
55 {
56 "$project": {
57 "_id": 1,
58 "title": 1,
59 "plot": 1,
60 "genres": 1,
61 "score": { "$meta": "searchScore" }
62 }
63 }
64])
1[
2 {
3 _id: ObjectId('573a139af29313caabcefcce'),
4 plot: 'Adaption of the famous Oscar Wilde tale about a young American girl that helps a British ghost find rest and forgiveness.',
5 genres: [ 'Family', 'Drama', 'Fantasy' ],
6 title: 'The Canterville Ghost',
7 score: 5.909613132476807
8 },
9 {
10 _id: ObjectId('573a13d8f29313caabda5dc1'),
11 plot: 'The Little Ghost lives in the castle over looking a small town and awakens for precisely one hour after the clock strikes midnight. Follow him on this adventure to see his first sunrise ever!',
12 genres: [ 'Family', 'Fantasy' ],
13 title: 'The Little Ghost',
14 score: 5.367666244506836
15 },
16 {
17 _id: ObjectId('573a13c0f29313caabd6139d'),
18 plot: 'Renowned "ghost hunter", Carter Simms is paid to conduct a paranormal investigation of a supposedly haunted house. Along with a cameraman, a reporter, and a spiritual advocate, she embarks on a three night journey into terror.',
19 genres: [ 'Horror', 'Thriller' ],
20 title: 'Death of a Ghost Hunter',
21 score: 4.676314353942871
22 },
23 {
24 _id: ObjectId('573a1398f29313caabcebf6f'),
25 plot: 'After an accident leaves a young man dead, his spirit stays behind to warn his lover of impending danger, with the help of a reluctant psychic.',
26 genres: [ 'Drama', 'Fantasy', 'Romance' ],
27 title: 'Ghost',
28 score: 3.9638845920562744
29 },
30 {
31 _id: ObjectId('573a13cdf29313caabd83c08'),
32 plot: "A man tries to solve his lover's murder by communicating with her spirit through the help of a medium.",
33 genres: [ 'Drama', 'Fantasy', 'Mystery' ],
34 title: 'Ghost',
35 score: 3.9638845920562744
36 },
37 {
38 _id: ObjectId('573a13cef29313caabd873a2'),
39 plot: "A man tries to solve his lover's murder by communicating with her spirit through the help of a medium.",
40 genres: [ 'Drama', 'Fantasy', 'Mystery' ],
41 title: 'Ghost',
42 score: 3.9638845920562744
43 },
44 {
45 _id: ObjectId('573a13c3f29313caabd6a149'),
46 plot: 'What kind of scenes in a horror film scares you the most? When a ghost appears totally unexpectedly? When the main character does not see the ghost sneaking up behind him? When at the very ...',
47 genres: [ 'Horror', 'Thriller' ],
48 title: 'Coming Soon',
49 score: 3.526711940765381
50 },
51 {
52 _id: ObjectId('573a1397f29313caabce7ea1'),
53 plot: "Four successful elderly gentlemen, members of the Chowder Society, share a gruesome, 50-year old secret. When one of Edward Wanderley's twin sons dies in a bizarre accident, the group ...",
54 genres: [ 'Drama', 'Horror', 'Thriller' ],
55 title: 'Ghost Story',
56 score: 3.3177831172943115
57 },
58 {
59 _id: ObjectId('573a13a4f29313caabd117df'),
60 plot: 'Stunt motorcyclist Johnny Blaze gives up his soul to become a hellblazing vigilante, to fight against power hungry Blackheart, the son of the devil himself.',
61 genres: [ 'Action', 'Fantasy', 'Thriller' ],
62 title: 'Ghost Rider',
63 score: 3.3177831172943115
64 },
65 {
66 _id: ObjectId('573a13a6f29313caabd185dc'),
67 plot: 'A salvage crew that discovers a long-lost 1962 passenger ship floating lifeless in a remote region of the Bering Sea soon notices, as they prepare to tow it back to land, that "strange things" happen...',
68 genres: [ 'Horror', 'Mystery' ],
69 title: 'Ghost Ship',
70 score: 3.3177831172943115
71 }
72]

The movie documents in the results contain the query term ghost in the plot or title field and aren't in the Comedy genre. MongoDB Search didn't return documents in the Comedy genre with the term ghost in the plot or title field because those documents didn't rank in the top 10 documents since the query reduced the score of those documents by 50%.

1

Open MongoDB Compass and connect to your cluster. For detailed instructions on connecting, see Connect to a Cluster via Compass.

2

On the Database screen, click the sample_mflix database, then click the movies collection.

3

This query uses the following pipeline stages:

  • Searches for movies that contain the term ghost in the plot or title (must clause) and aren't in the comedy genre (mustNot clause).

  • Searches for movies that contain the term ghost in the plot or title (must clause) and are in the comedy genre (filter clause), but reduces the score by 50% (boost).

Limits the number of results to 10 documents.

  • Includes only the _id, title, plot, and genres fields from the documents in the results.

  • Adds a field named score that shows the score in the results.

To run this query, perform the following steps in MongoDB Compass:

  1. Click the Aggregations tab.

  2. Click Select..., then configure each of the following pipeline stages by selecting the stage from the dropdown and adding the query for that stage.

    Tip

    Click Add Stage to add additional stages.

    Pipeline Stage
    Query

    $search

    {
    "index": "default",
    "compound": {
    "should": [
    {
    "compound":{
    "must": [
    {
    "text": {
    "query": "ghost",
    "path": ["plot","title"]
    }
    }
    ],
    "mustNot": [
    {
    "text": {
    "query": "Comedy",
    "path": ["genres"]
    }
    }
    ]
    }
    },
    {
    "compound":{
    "must":[
    {
    "text": {
    "query": "ghost",
    "path": ["plot","title"]
    }
    }
    ],
    "filter": [
    {
    "text": {
    "query": "Comedy",
    "path": ["genres"]
    }
    }
    ],
    "score": { "boost": { "value": 0.5} }
    }
    }
    ]
    }
    }

    $limit

    10

    $project

    {
    "_id": 1,
    "title": 1,
    "plot": 1,
    "genres": 1,
    "score": { "$meta": "searchScore" }
    }

    If you enabled Auto Preview, MongoDB Compass displays the following documents next to the $project pipeline stage:

    1_id: ObjectId('573a139af29313caabcefcce'),
    2plot: 'Adaption of the famous Oscar Wilde tale about a young American girl that helps a British ghost find rest and forgiveness.',
    3genres: [ 'Family', 'Drama', 'Fantasy' ],
    4title: 'The Canterville Ghost',
    5score: 5.909613132476807
    6
    7_id: ObjectId('573a13d8f29313caabda5dc1'),
    8plot: 'The Little Ghost lives in the castle over looking a small town and awakens for precisely one hour after the clock strikes midnight. Follow him on this adventure to see his first sunrise ever!',
    9genres: [ 'Family', 'Fantasy' ],
    10title: 'The Little Ghost',
    11score: 5.367666244506836
    12
    13_id: ObjectId('573a13c0f29313caabd6139d'),
    14plot: 'Renowned "ghost hunter", Carter Simms is paid to conduct a paranormal investigation of a supposedly haunted house. Along with a cameraman, a reporter, and a spiritual advocate, she embarks on a three night journey into terror.',
    15genres: [ 'Horror', 'Thriller' ],
    16title: 'Death of a Ghost Hunter',
    17score: 4.676314353942871
    18
    19_id: ObjectId('573a1398f29313caabcebf6f'),
    20plot: 'After an accident leaves a young man dead, his spirit stays behind to warn his lover of impending danger, with the help of a reluctant psychic.',
    21genres: [ 'Drama', 'Fantasy', 'Romance' ],
    22title: 'Ghost',
    23score: 3.9638845920562744
    24
    25_id: ObjectId('573a13cdf29313caabd83c08'),
    26plot: "A man tries to solve his lover's murder by communicating with her spirit through the help of a medium.",
    27genres: [ 'Drama', 'Fantasy', 'Mystery' ],
    28title: 'Ghost',
    29score: 3.9638845920562744
    30
    31_id: ObjectId('573a13cef29313caabd873a2'),
    32plot: "A man tries to solve his lover's murder by communicating with her spirit through the help of a medium.",
    33genres: [ 'Drama', 'Fantasy', 'Mystery' ],
    34title: 'Ghost',
    35score: 3.9638845920562744
    36
    37_id: ObjectId('573a13c3f29313caabd6a149'),
    38plot: 'What kind of scenes in a horror film scares you the most? When a ghost appears totally unexpectedly? When the main character does not see the ghost sneaking up behind him? When at the very ...',
    39genres: [ 'Horror', 'Thriller' ],
    40title: 'Coming Soon',
    41score: 3.526711940765381
    42
    43_id: ObjectId('573a1397f29313caabce7ea1'),
    44plot: "Four successful elderly gentlemen, members of the Chowder Society, share a gruesome, 50-year old secret. When one of Edward Wanderley's twin sons dies in a bizarre accident, the group ...",
    45genres: [ 'Drama', 'Horror', 'Thriller' ],
    46title: 'Ghost Story',
    47score: 3.3177831172943115
    48
    49_id: ObjectId('573a13a4f29313caabd117df'),
    50plot: 'Stunt motorcyclist Johnny Blaze gives up his soul to become a hellblazing vigilante, to fight against power hungry Blackheart, the son of the devil himself.',
    51genres: [ 'Action', 'Fantasy', 'Thriller' ],
    52title: 'Ghost Rider',
    53score: 3.3177831172943115
    54
    55_id: ObjectId('573a13a6f29313caabd185dc'),
    56plot: 'A salvage crew that discovers a long-lost 1962 passenger ship floating lifeless in a remote region of the Bering Sea soon notices, as they prepare to tow it back to land, that "strange things" happen...',
    57genres: [ 'Horror', 'Mystery' ],
    58title: 'Ghost Ship',
    59score: 3.3177831172943115

    The movie documents in the results contain the query term ghost in the plot or title field and aren't in the Comedy genre. MongoDB Search didn't return documents in the Comedy genre with the term ghost in the plot or title field because those documents didn't rank in the top 10 documents since the query reduced the score of those documents by 50%.

1
  1. Create a new directory called compound-bury-results and initialize your project with the dotnet new command.

    mkdir compound-bury-results
    cd compound-bury-results
    dotnet new console
  2. Add the .NET/C# driver to your project as a dependency.

    dotnet add package MongoDB.Driver
2

This query uses the following pipeline stages:

  • Searches for movies that contain the term ghost in the plot or title (must clause) and aren't in the comedy genre (mustNot clause).

  • Searches for movies that contain the term ghost in the plot or title (must clause) and are in the comedy genre (filter clause), but reduces the score by 50% (boost).

Limits the number of results to 10 documents.

  • Includes only the _id, title, plot, and genres fields from the documents in the results.

  • Adds a field named score that shows the score in the results.

1using MongoDB.Bson;
2using MongoDB.Bson.Serialization.Attributes;
3using MongoDB.Bson.Serialization.Conventions;
4using MongoDB.Driver;
5using MongoDB.Driver.Search;
6
7public class BuryGenreCompoundExample
8{
9 private const string MongoConnectionString = "<connection-string>";
10
11 public static void Main(string[] args)
12 {
13 // allow automapping of the camelCase database fields to our MovieDocument
14 var camelCaseConvention = new ConventionPack { new CamelCaseElementNameConvention() };
15 ConventionRegistry.Register("CamelCase", camelCaseConvention, type => true);
16
17 // connect to your Atlas cluster
18 var mongoClient = new MongoClient(MongoConnectionString);
19 var mflixDatabase = mongoClient.GetDatabase("sample_mflix");
20 var moviesCollection = mflixDatabase.GetCollection<MovieDocument>("movies");
21
22 // define and run pipeline
23 var results = moviesCollection.Aggregate()
24 .Search(Builders<MovieDocument>.Search.Compound()
25 .Should(Builders<MovieDocument>.Search.Compound()
26 .Must(Builders<MovieDocument>.Search.Text(
27 Builders<MovieDocument>.SearchPath.Multi(movie => movie.Title, movie => movie.Plot), "ghost"))
28 .MustNot(Builders<MovieDocument>.Search.Text(movie => movie.Genres, "Comedy"))
29 )
30 .Should(Builders<MovieDocument>.Search.Compound()
31 .Must(Builders<MovieDocument>.Search.Text(
32 Builders<MovieDocument>.SearchPath.Multi(movie => movie.Title, movie => movie.Plot), "ghost"))
33 .Filter(Builders<MovieDocument>.Search.Text(movie => movie.Genres, "Comedy", score: new SearchScoreDefinitionBuilder<MovieDocument>().Boost(0.5)))
34 ),
35 indexName: "default")
36 .Project<MovieDocument>(Builders<MovieDocument>.Projection
37 .Include(movie => movie.Plot)
38 .Include(movie => movie.Title)
39 .Include(movie => movie.Id)
40 .Include(movie => movie.Genres)
41 .MetaSearchScore("score"))
42 .Limit(10)
43 .ToList();
44
45 // print results
46 foreach (var movie in results)
47 {
48 Console.WriteLine(movie.ToJson());
49 }
50 }
51}
52
53[BsonIgnoreExtraElements]
54public class MovieDocument
55{
56 [BsonIgnoreIfDefault]
57 public ObjectId Id { get; set; }
58 public string Plot { get; set; }
59 public string Title { get; set; }
60 public string[] Genres { get; set; }
61 public double Score { get; set; }
62}
3

Ensure that your connection string includes your database user's credentials. To learn more, see Connect to a Cluster via Client Libraries.

4
dotnet run compound-bury-results.csproj
{ "_id" : ObjectId("573a139af29313caabcefcce"), "plot" : "Adaption of the famous Oscar Wilde tale about a young American girl that helps a British ghost find rest and forgiveness.", "title" : "The Canterville Ghost", "genres" : ["Family", "Drama", "Fantasy"], "score" : 5.9096131324768066 }
{ "_id" : ObjectId("573a13d8f29313caabda5dc1"), "plot" : "The Little Ghost lives in the castle over looking a small town and awakens for precisely one hour after the clock strikes midnight. Follow him on this adventure to see his first sunrise ever!", "title" : "The Little Ghost", "genres" : ["Family", "Fantasy"], "score" : 5.3676662445068359 }
{ "_id" : ObjectId("573a13c0f29313caabd6139d"), "plot" : "Renowned \"ghost hunter\", Carter Simms is paid to conduct a paranormal investigation of a supposedly haunted house. Along with a cameraman, a reporter, and a spiritual advocate, she embarks on a three night journey into terror.", "title" : "Death of a Ghost Hunter", "genres" : ["Horror", "Thriller"], "score" : 4.6763143539428711 }
{ "_id" : ObjectId("573a1398f29313caabcebf6f"), "plot" : "After an accident leaves a young man dead, his spirit stays behind to warn his lover of impending danger, with the help of a reluctant psychic.", "title" : "Ghost", "genres" : ["Drama", "Fantasy", "Romance"], "score" : 3.9638845920562744 }
{ "_id" : ObjectId("573a13cdf29313caabd83c08"), "plot" : "A man tries to solve his lover's murder by communicating with her spirit through the help of a medium.", "title" : "Ghost", "genres" : ["Drama", "Fantasy", "Mystery"], "score" : 3.9638845920562744 }
{ "_id" : ObjectId("573a13cef29313caabd873a2"), "plot" : "A man tries to solve his lover's murder by communicating with her spirit through the help of a medium.", "title" : "Ghost", "genres" : ["Drama", "Fantasy", "Mystery"], "score" : 3.9638845920562744 }
{ "_id" : ObjectId("573a13c3f29313caabd6a149"), "plot" : "What kind of scenes in a horror film scares you the most? When a ghost appears totally unexpectedly? When the main character does not see the ghost sneaking up behind him? When at the very ...", "title" : "Coming Soon", "genres" : ["Horror", "Thriller"], "score" : 3.5267119407653809 }
{ "_id" : ObjectId("573a1398f29313caabce912c"), "plot" : "Three unemployed parapsychology professors set up shop as a unique ghost removal service.", "title" : "Ghostbusters", "genres" : ["Comedy", "Fantasy"], "score" : 3.5241782665252686 }
{ "_id" : ObjectId("573a139cf29313caabcf5a48"), "plot" : "Casper, a ghost, teams up with Wendy, a witch, against an evil warlock.", "title" : "Casper Meets Wendy", "genres" : ["Adventure", "Comedy", "Family"], "score" : 3.5241782665252686 }
{ "_id" : ObjectId("573a13bdf29313caabd58274"), "plot" : "Banku, his mother, Anjali Sharma and father move in to their new house -- the Nath villa, unaware of the fact that the house is inhabited by a ghost. It is learnt the ghost is not too happy...", "title" : "Bhoothnath", "genres" : ["Comedy", "Drama", "Fantasy"], "score" : 3.4605300426483154 }

The movie documents in the results contain the query term ghost in the plot or title field and aren't in the Comedy genre. MongoDB Search didn't return documents in the Comedy genre with the term ghost in the plot or title field because those documents didn't rank in the top 10 documents since the query reduced the score of those documents by 50%.

1
2

This query uses the following pipeline stages:

  • Searches for movies that contain the term ghost in the plot or title (must clause) and aren't in the comedy genre (mustNot clause).

  • Searches for movies that contain the term ghost in the plot or title (must clause) and are in the comedy genre (filter clause), but reduces the score by 50% (boost).

Limits the number of results to 10 documents.

  • Includes only the _id, title, plot, and genres fields from the documents in the results.

  • Adds a field named score that shows the score in the results.

1package main
2
3import (
4 "context"
5 "fmt"
6 "time"
7
8 "go.mongodb.org/mongo-driver/v2/bson"
9 "go.mongodb.org/mongo-driver/v2/mongo"
10 "go.mongodb.org/mongo-driver/v2/mongo/options"
11)
12
13// define structure of movies collection
14type MovieCollection struct {
15 title string `bson:"Title,omitempty"`
16 plot string `bson:"Plot,omitempty"`
17}
18
19func main() {
20 var err error
21 // connect to the Atlas cluster and set a maximum operation time
22 ctx := context.Background()
23 opts := options.Client().
24 SetTimeout(5 * time.Second).
25 ApplyURI("<connection-string>")
26
27 client, err := mongo.Connect(opts)
28 if err != nil {
29 panic(err)
30 }
31 defer client.Disconnect(ctx)
32 // set namespace
33 collection := client.Database("sample_mflix").Collection("movies")
34 // define pipeline
35 searchStage := bson.D{{"$search", bson.D{
36 {"index", "default"},
37 {"compound", bson.D{
38 {"should", bson.A{
39 bson.D{{"compound", bson.D{
40 {"must", bson.A{
41 bson.D{{"text", bson.D{
42 {"query", "ghost"},
43 {"path", bson.A{"plot", "title"}},
44 }}},
45 }},
46 {"mustNot", bson.A{
47 bson.D{{"text", bson.D{
48 {"query", "Comedy"},
49 {"path", bson.A{"genres"}},
50 }}},
51 }},
52 }}},
53 bson.D{{"compound", bson.D{
54 {"must", bson.A{
55 bson.D{{"text", bson.D{
56 {"query", "ghost"},
57 {"path", bson.A{"plot", "title"}},
58 }}},
59 }},
60 {"filter", bson.A{
61 bson.D{{"text", bson.D{
62 {"query", "Comedy"},
63 {"path", bson.A{"genres"}},
64 }}},
65 }},
66 {"score", bson.D{{"boost", bson.D{{"value", 0.5}}}}},
67 }}},
68 }},
69 }},
70 }}}
71 limitStage := bson.D{{"$limit", 10}}
72 projectStage := bson.D{{"$project", bson.D{{"title", 1}, {"plot", 1}, {"_id", 0}, {"genres", 1}, {"score", bson.D{{"$meta", "searchScore"}}}}}}
73 // run pipeline
74 cursor, err := collection.Aggregate(ctx, mongo.Pipeline{searchStage, limitStage, projectStage})
75 if err != nil {
76 panic(err)
77 }
78 // print results
79 var results []bson.D
80 if err = cursor.All(context.TODO(), &results); err != nil {
81 panic(err)
82 }
83 for _, result := range results {
84 fmt.Println(result)
85 }
86}
3

Ensure that your connection string includes your database user's credentials. To learn more, see Connect to a Cluster via Client Libraries.

4
go run compound-bury-results.go
[{plot Adaption of the famous Oscar Wilde tale about a young American girl that helps a British ghost find rest and forgiveness.} {genres [Family Drama Fantasy]} {title The Canterville Ghost} {score 5.909613132476807}]
[{plot The Little Ghost lives in the castle over looking a small town and awakens for precisely one hour after the clock strikes midnight. Follow him on this adventure to see his first sunrise ever!} {genres [Family Fantasy]} {title The Little Ghost} {score 5.367666244506836}]
[{plot Renowned "ghost hunter", Carter Simms is paid to conduct a paranormal investigation of a supposedly haunted house. Along with a cameraman, a reporter, and a spiritual advocate, she embarks on a three night journey into terror.} {genres [Horror Thriller]} {title Death of a Ghost Hunter} {score 4.676314353942871}]
[{plot After an accident leaves a young man dead, his spirit stays behind to warn his lover of impending danger, with the help of a reluctant psychic.} {genres [Drama Fantasy Romance]} {title Ghost} {score 3.9638845920562744}]
[{plot A man tries to solve his lover's murder by communicating with her spirit through the help of a medium.} {genres [Drama Fantasy Mystery]} {title Ghost} {score 3.9638845920562744}]
[{plot A man tries to solve his lover's murder by communicating with her spirit through the help of a medium.} {genres [Drama Fantasy Mystery]} {title Ghost} {score 3.9638845920562744}]
[{plot What kind of scenes in a horror film scares you the most? When a ghost appears totally unexpectedly? When the main character does not see the ghost sneaking up behind him? When at the very ...} {genres [Horror Thriller]} {title Coming Soon} {score 3.526711940765381}]
[{plot Four successful elderly gentlemen, members of the Chowder Society, share a gruesome, 50-year old secret. When one of Edward Wanderley's twin sons dies in a bizarre accident, the group ...} {genres [Drama Horror Thriller]} {title Ghost Story} {score 3.3177831172943115}]
[{plot Stunt motorcyclist Johnny Blaze gives up his soul to become a hellblazing vigilante, to fight against power hungry Blackheart, the son of the devil himself.} {genres [Action Fantasy Thriller]} {title Ghost Rider} {score 3.3177831172943115}]
[{plot A salvage crew that discovers a long-lost 1962 passenger ship floating lifeless in a remote region of the Bering Sea soon notices, as they prepare to tow it back to land, that "strange things" happen...} {genres [Horror Mystery]} {title Ghost Ship} {score 3.3177831172943115}]

The movie documents in the results contain the query term ghost in the plot or title field and aren't in the Comedy genre. MongoDB Search didn't return documents in the Comedy genre with the term ghost in the plot or title field because those documents didn't rank in the top 10 documents since the query reduced the score of those documents by 50%.

1

junit

4.11 or higher version

mongodb-driver-sync

4.3.0 or higher version

slf4j-log4j12

1.7.30 or higher version

2
3

This query uses the following pipeline stages:

  • Searches for movies that contain the term ghost in the plot or title (must clause) and aren't in the comedy genre (mustNot clause).

  • Searches for movies that contain the term ghost in the plot or title (must clause) and are in the comedy genre (filter clause), but reduces the score by 50% (boost).

Limits the number of results to 10 documents.

  • Includes only the _id, title, plot, and genres fields from the documents in the results.

  • Adds a field named score that shows the score in the results.

1import java.util.Arrays;
2import static com.mongodb.client.model.Aggregates.limit;
3import static com.mongodb.client.model.Aggregates.project;
4import static com.mongodb.client.model.Projections.*;
5import com.mongodb.client.MongoClient;
6import com.mongodb.client.MongoClients;
7import com.mongodb.client.MongoCollection;
8import com.mongodb.client.MongoDatabase;
9
10import org.bson.Document;
11
12public class CompoundBuryQuery {
13 public static void main( String[] args ) {
14 // define query
15 Document agg =
16 new Document("$search",
17 new Document("index", "default")
18 .append("compound",
19 new Document("should", Arrays.asList(new Document("compound",
20 new Document("must", Arrays.asList(new Document("text",
21 new Document("query", "ghost")
22 .append("path", Arrays.asList("plot", "title")))))
23 .append("mustNot", Arrays.asList(new Document("text",
24 new Document("query", "Comedy")
25 .append("path", Arrays.asList("genres")))))
26 ),
27 new Document("compound",
28 new Document("must", Arrays.asList(new Document("text",
29 new Document("query", "ghost")
30 .append("path", Arrays.asList("plot", "title")))))
31 .append("filter", Arrays.asList(new Document("text",
32 new Document("query", "Comedy")
33 .append("path", Arrays.asList("genres")))))
34 .append("score", new Document("boost",
35 new Document("value", 0.5d))))))
36 )
37 );
38 // specify connection
39 String uri = "<connection-string>";
40 // establish connection and set namespace
41 try (MongoClient mongoClient = MongoClients.create(uri)) {
42 MongoDatabase database = mongoClient.getDatabase("sample_mflix");
43 MongoCollection<Document> collection = database.getCollection("movies");
44 // run query and print results
45 collection.aggregate(Arrays.asList(agg,
46 limit(10),
47 project(fields(
48 include("title", "plot", "genres", "_id"),
49 computed("score", new Document("$meta", "searchScore"))))))
50 .forEach(doc -> System.out.println(doc.toJson()));
51 }
52 }
53}
4

Ensure that your connection string includes your database user's credentials. To learn more, see Connect to a Cluster via Client Libraries.

5
javac CompoundBuryQuery.java
{"_id": {"$oid": "573a139af29313caabcefcce"}, "plot": "Adaption of the famous Oscar Wilde tale about a young American girl that helps a British ghost find rest and forgiveness.", "genres": ["Family", "Drama", "Fantasy"], "title": "The Canterville Ghost", "score": 5.909613132476807}
{"_id": {"$oid": "573a13d8f29313caabda5dc1"}, "plot": "The Little Ghost lives in the castle over looking a small town and awakens for precisely one hour after the clock strikes midnight. Follow him on this adventure to see his first sunrise ever!", "genres": ["Family", "Fantasy"], "title": "The Little Ghost", "score": 5.367666244506836}
{"_id": {"$oid": "573a13c0f29313caabd6139d"}, "plot": "Renowned \"ghost hunter\", Carter Simms is paid to conduct a paranormal investigation of a supposedly haunted house. Along with a cameraman, a reporter, and a spiritual advocate, she embarks on a three night journey into terror.", "genres": ["Horror", "Thriller"], "title": "Death of a Ghost Hunter", "score": 4.676314353942871}
{"_id": {"$oid": "573a1398f29313caabcebf6f"}, "plot": "After an accident leaves a young man dead, his spirit stays behind to warn his lover of impending danger, with the help of a reluctant psychic.", "genres": ["Drama", "Fantasy", "Romance"], "title": "Ghost", "score": 3.9638845920562744}
{"_id": {"$oid": "573a13cdf29313caabd83c08"}, "plot": "A man tries to solve his lover's murder by communicating with her spirit through the help of a medium.", "genres": ["Drama", "Fantasy", "Mystery"], "title": "Ghost", "score": 3.9638845920562744}
{"_id": {"$oid": "573a13cef29313caabd873a2"}, "plot": "A man tries to solve his lover's murder by communicating with her spirit through the help of a medium.", "genres": ["Drama", "Fantasy", "Mystery"], "title": "Ghost", "score": 3.9638845920562744}
{"_id": {"$oid": "573a13c3f29313caabd6a149"}, "plot": "What kind of scenes in a horror film scares you the most? When a ghost appears totally unexpectedly? When the main character does not see the ghost sneaking up behind him? When at the very ...", "genres": ["Horror", "Thriller"], "title": "Coming Soon", "score": 3.526711940765381}
{"_id": {"$oid": "573a1397f29313caabce7ea1"}, "plot": "Four successful elderly gentlemen, members of the Chowder Society, share a gruesome, 50-year old secret. When one of Edward Wanderley's twin sons dies in a bizarre accident, the group ...", "genres": ["Drama", "Horror", "Thriller"], "title": "Ghost Story", "score": 3.3177831172943115}
{"_id": {"$oid": "573a13a4f29313caabd117df"}, "plot": "Stunt motorcyclist Johnny Blaze gives up his soul to become a hellblazing vigilante, to fight against power hungry Blackheart, the son of the devil himself.", "genres": ["Action", "Fantasy", "Thriller"], "title": "Ghost Rider", "score": 3.3177831172943115}
{"_id": {"$oid": "573a13a6f29313caabd185dc"}, "plot": "A salvage crew that discovers a long-lost 1962 passenger ship floating lifeless in a remote region of the Bering Sea soon notices, as they prepare to tow it back to land, that \"strange things\" happen...", "genres": ["Horror", "Mystery"], "title": "Ghost Ship", "score": 3.3177831172943115}

The movie documents in the results contain the query term ghost in the plot or title field and aren't in the Comedy genre. MongoDB Search didn't return documents in the Comedy genre with the term ghost in the plot or title field because those documents didn't rank in the top 10 documents since the query reduced the score of those documents by 50%.

1

mongodb-driver-kotlin-coroutine

4.10.0 or higher version

2
3

This query uses the following pipeline stages:

  • Searches for movies that contain the term ghost in the plot or title (must clause) and aren't in the comedy genre (mustNot clause).

  • Searches for movies that contain the term ghost in the plot or title (must clause) and are in the comedy genre (filter clause), but reduces the score by 50% (boost).

Limits the number of results to 10 documents.

  • Includes only the _id, title, plot, and genres fields from the documents in the results.

  • Adds a field named score that shows the score in the results.

1import com.mongodb.client.model.Aggregates.limit
2import com.mongodb.client.model.Aggregates.project
3import com.mongodb.client.model.Projections.*
4import com.mongodb.kotlin.client.coroutine.MongoClient
5import kotlinx.coroutines.runBlocking
6import org.bson.Document
7
8fun main() {
9 // establish connection and set namespace
10 val uri = "<connection-string>"
11 val mongoClient = MongoClient.create(uri)
12 val database = mongoClient.getDatabase("sample_mflix")
13 val collection = database.getCollection<Document>("movies")
14
15 runBlocking {
16 // define clauses
17 val mustClause = listOf(
18 Document("text",
19 Document("query", "ghost")
20 .append("path", listOf("plot","title"))
21 )
22 )
23
24 val mustNotClauseAndFilterClause = listOf(
25 Document("text",
26 Document("query", "Comedy")
27 .append("path", listOf("genres"))
28 )
29 )
30
31 val compound1 = Document("must", mustClause)
32 .append("mustNot", mustNotClauseAndFilterClause)
33
34 val compound2 = Document("must", mustClause)
35 .append("filter", mustNotClauseAndFilterClause)
36 .append("score",
37 Document("boost",
38 Document("value", 0.5)
39 )
40 )
41
42 val agg = Document("\$search",
43 Document("index", "default")
44 .append("compound", Document("should", listOf(
45 Document("compound", compound1),
46 Document("compound", compound2)
47 )))
48 )
49
50 val resultsFlow = collection.aggregate<Document>(
51 listOf(
52 agg,
53 limit(10),
54 project(fields(
55 include("title", "plot", "genres"),
56 computed("score", Document("\$meta", "searchScore"))
57 ))
58 )
59 )
60 resultsFlow.collect { println(it) }
61 }
62 mongoClient.close()
63}
4

Ensure that your connection string includes your database user's credentials. To learn more, see Connect to a Cluster via Client Libraries.

5

When you run the CompoundBuryQuery.kt program in your IDE, it prints the following documents:

dotnet run compound-bury-results.csproj
Document{{_id=573a139af29313caabcefcce, plot=Adaption of the famous Oscar Wilde tale about a young American girl that helps a British ghost find rest and forgiveness., genres=[Family, Drama, Fantasy], title=The Canterville Ghost, score=5.909613132476807}}
Document{{_id=573a13d8f29313caabda5dc1, plot=The Little Ghost lives in the castle over looking a small town and awakens for precisely one hour after the clock strikes midnight. Follow him on this adventure to see his first sunrise ever!, genres=[Family, Fantasy], title=The Little Ghost, score=5.367666244506836}}
Document{{_id=573a13c0f29313caabd6139d, plot=Renowned "ghost hunter", Carter Simms is paid to conduct a paranormal investigation of a supposedly haunted house. Along with a cameraman, a reporter, and a spiritual advocate, she embarks on a three night journey into terror., genres=[Horror, Thriller], title=Death of a Ghost Hunter, score=4.676314353942871}}
Document{{_id=573a1398f29313caabcebf6f, plot=After an accident leaves a young man dead, his spirit stays behind to warn his lover of impending danger, with the help of a reluctant psychic., genres=[Drama, Fantasy, Romance], title=Ghost, score=3.9638845920562744}}
Document{{_id=573a13cdf29313caabd83c08, plot=A man tries to solve his lover's murder by communicating with her spirit through the help of a medium., genres=[Drama, Fantasy, Mystery], title=Ghost, score=3.9638845920562744}}
Document{{_id=573a13cef29313caabd873a2, plot=A man tries to solve his lover's murder by communicating with her spirit through the help of a medium., genres=[Drama, Fantasy, Mystery], title=Ghost, score=3.9638845920562744}}
Document{{_id=573a13c3f29313caabd6a149, plot=What kind of scenes in a horror film scares you the most? When a ghost appears totally unexpectedly? When the main character does not see the ghost sneaking up behind him? When at the very ..., genres=[Horror, Thriller], title=Coming Soon, score=3.526711940765381}}
Document{{_id=573a1397f29313caabce7ea1, plot=Four successful elderly gentlemen, members of the Chowder Society, share a gruesome, 50-year old secret. When one of Edward Wanderley's twin sons dies in a bizarre accident, the group ..., genres=[Drama, Horror, Thriller], title=Ghost Story, score=3.3177831172943115}}
Document{{_id=573a13a4f29313caabd117df, plot=Stunt motorcyclist Johnny Blaze gives up his soul to become a hellblazing vigilante, to fight against power hungry Blackheart, the son of the devil himself., genres=[Action, Fantasy, Thriller], title=Ghost Rider, score=3.3177831172943115}}
Document{{_id=573a13a6f29313caabd185dc, plot=A salvage crew that discovers a long-lost 1962 passenger ship floating lifeless in a remote region of the Bering Sea soon notices, as they prepare to tow it back to land, that "strange things" happen..., genres=[Horror, Mystery], title=Ghost Ship, score=3.3177831172943115}}

The movie documents in the results contain the query term ghost in the plot or title field and aren't in the Comedy genre. MongoDB Search didn't return documents in the Comedy genre with the term ghost in the plot or title field because those documents didn't rank in the top 10 documents since the query reduced the score of those documents by 50%.

1
2

This query uses the following pipeline stages:

  • Searches for movies that contain the term ghost in the plot or title (must clause) and aren't in the comedy genre (mustNot clause).

  • Searches for movies that contain the term ghost in the plot or title (must clause) and are in the comedy genre (filter clause), but reduces the score by 50% (boost).

Limits the number of results to 10 documents.

  • Includes only the _id, title, plot, and genres fields from the documents in the results.

  • Adds a field named score that shows the score in the results.

1const { MongoClient } = require("mongodb");
2
3// connect to your Atlas cluster
4const uri = "<connection-string>";
5const client = new MongoClient(uri);
6
7async function run() {
8 try {
9 await client.connect();
10
11 // set namespace
12 const database = client.db("sample_mflix");
13 const coll = database.collection("movies");
14
15 // define pipeline
16 const agg = [
17 {
18 "$search": {
19 "index": "default",
20 "compound": {
21 "should": [
22 {
23 "compound": {
24 "must": [
25 {
26 "text": {
27 "query": "ghost",
28 "path": [
29 "plot", "title"
30 ]
31 }
32 }
33 ],
34 "mustNot": [
35 {
36 "text": {
37 "query": "Comedy",
38 "path": [
39 "genres"
40 ]
41 }
42 }
43 ]
44 }
45 }, {
46 "compound": {
47 "must": [
48 {
49 "text": {
50 "query": "ghost",
51 "path": [
52 "plot", "title"
53 ]
54 }
55 }
56 ],
57 "filter": [
58 {
59 "text": {
60 "query": "Comedy",
61 "path": [
62 "genres"
63 ]
64 }
65 }
66 ],
67 "score": { "boost": { "value": 0.5 } }
68 }
69 }
70 ]
71 }
72 }
73 }, {
74 "$limit": 10
75 }, {
76 "$project": {
77 "_id": 1,
78 "title": 1,
79 "plot": 1,
80 "genres": 1,
81 "score": { "$meta": "searchScore" }
82 }
83 }
84 ];
85
86 // run pipeline
87 const result = coll.aggregate(agg);
88
89 // print results
90 await result.forEach((doc) => console.dir(JSON.stringify(doc)));
91 } finally {
92 await client.close();
93 }
94}
95run().catch(console.dir);
3

Ensure that your connection string includes your database user's credentials. To learn more, see Connect to a Cluster via Client Libraries.

4

Run the following command to query your collection:

node compound-bury-results.js
{"_id":"573a139af29313caabcefcce","plot":"Adaption of the famous Oscar Wilde tale about a young American girl that helps a British ghost find rest and forgiveness.","genres":["Family","Drama","Fantasy"],"title":"The Canterville Ghost","score":5.909613132476807}
{"_id":"573a13d8f29313caabda5dc1","plot":"The Little Ghost lives in the castle over looking a small town and awakens for precisely one hour after the clock strikes midnight. Follow him on this adventure to see his first sunrise ever!","genres":["Family","Fantasy"],"title":"The Little Ghost","score":5.367666244506836}
{"_id":"573a13c0f29313caabd6139d","plot":"Renowned \\"ghost hunter\\", Carter Simms is paid to conduct a paranormal investigation of a supposedly haunted house. Along with a cameraman, a reporter, and a spiritual advocate, she embarks on a three night journey into terror.","genres":["Horror","Thriller"],"title":"Death of a Ghost Hunter","score":4.676314353942871}
{"_id":"573a1398f29313caabcebf6f","plot":"After an accident leaves a young man dead, his spirit stays behind to warn his lover of impending danger, with the help of a reluctant psychic.","genres":["Drama","Fantasy","Romance"],"title":"Ghost","score":3.9638845920562744}
{"_id":"573a13cdf29313caabd83c08","plot":"A man tries to solve his lovers murder by communicating with her spirit through the help of a medium.","genres":["Drama","Fantasy","Mystery"],"title":"Ghost","score":3.9638845920562744}
{"_id":"573a13cef29313caabd873a2","plot":"A man tries to solve his lovers murder by communicating with her spirit through the help of a medium.","genres":["Drama","Fantasy","Mystery"],"title":"Ghost","score":3.9638845920562744}
{"_id":"573a13c3f29313caabd6a149","plot":"What kind of scenes in a horror film scares you the most? When a ghost appears totally unexpectedly? When the main character does not see the ghost sneaking up behind him? When at the very ...","genres":["Horror","Thriller"],"title":"Coming Soon","score":3.526711940765381}
{"_id":"573a1397f29313caabce7ea1","plot":"Four successful elderly gentlemen, members of the Chowder Society, share a gruesome, 50-year old secret. When one of Edward Wanderleys twin sons dies in a bizarre accident, the group ...","genres":["Drama","Horror","Thriller"],"title":"Ghost Story","score":3.3177831172943115}
{"_id":"573a13a4f29313caabd117df","plot":"Stunt motorcyclist Johnny Blaze gives up his soul to become a hellblazing vigilante, to fight against power hungry Blackheart, the son of the devil himself.","genres":["Action","Fantasy","Thriller"],"title":"Ghost Rider","score":3.3177831172943115}
{"_id":"573a13a6f29313caabd185dc","plot":"A salvage crew that discovers a long-lost 1962 passenger ship floating lifeless in a remote region of the Bering Sea soon notices, as they prepare to tow it back to land, that \\"strange things\\" happen...","genres":["Horror","Mystery"],"title":"Ghost Ship","score":3.3177831172943115}

The movie documents in the results contain the query term ghost in the plot or title field and aren't in the Comedy genre. MongoDB Search didn't return documents in the Comedy genre with the term ghost in the plot or title field because those documents didn't rank in the top 10 documents since the query reduced the score of those documents by 50%.

1
2

This query uses the following pipeline stages:

  • Searches for movies that contain the term ghost in the plot or title (must clause) and aren't in the comedy genre (mustNot clause).

  • Searches for movies that contain the term ghost in the plot or title (must clause) and are in the comedy genre (filter clause), but reduces the score by 50% (boost).

Limits the number of results to 10 documents.

  • Includes only the _id, title, plot, and genres fields from the documents in the results.

  • Adds a field named score that shows the score in the results.

1import pymongo
2import dns
3
4client = pymongo.MongoClient('<connection-string>')
5result = client['sample_mflix']['movies'].aggregate([
6 {
7 '$search': {
8 'index': 'default',
9 'compound': {
10 'should': [
11 {
12 'compound': {
13 'must': [
14 {
15 'text': {
16 'query': 'ghost',
17 'path': [ 'plot', 'title' ]
18 }
19 }
20 ],
21 'mustNot': [
22 {
23 'text': {
24 'query': 'Comedy',
25 'path': [ 'genres' ]
26 }
27 }
28 ]
29 }
30 }, {
31 'compound': {
32 'must': [
33 {
34 'text': {
35 'query': 'ghost',
36 'path': [ 'plot', 'title' ]
37 }
38 }
39 ],
40 'filter': [
41 {
42 'text': {
43 'query': 'Comedy',
44 'path': [ 'genres' ]
45 }
46 }
47 ],
48 'score': { 'boost': { 'value': 0.5 } }
49 }
50 }
51 ]
52 }
53 }
54 }, {
55 '$limit': 10
56 }, {
57 '$project': {
58 '_id': 1,
59 'title': 1,
60 'plot': 1,
61 'genres': 1,
62 'score': { '$meta': 'searchScore' }
63 }
64 }
65])
66
67for i in result:
68 print(i)
3

Ensure that your connection string includes your database user's credentials. To learn more, see Connect to a Cluster via Client Libraries.

4
python compound-bury-results.csproj
{'_id': ObjectId('573a139af29313caabcefcce'), 'plot': 'Adaption of the famous Oscar Wilde tale about a young American girl that helps a British ghost find rest and forgiveness.', 'genres': ['Family', 'Drama', 'Fantasy'], 'title': 'The Canterville Ghost', 'score': 5.909613132476807}
{'_id': ObjectId('573a13d8f29313caabda5dc1'), 'plot': 'The Little Ghost lives in the castle over looking a small town and awakens for precisely one hour after the clock strikes midnight. Follow him on this adventure to see his first sunrise ever!', 'genres': ['Family', 'Fantasy'], 'title': 'The Little Ghost', 'score': 5.367666244506836}
{'_id': ObjectId('573a13c0f29313caabd6139d'), 'plot': 'Renowned "ghost hunter", Carter Simms is paid to conduct a paranormal investigation of a supposedly haunted house. Along with a cameraman, a reporter, and a spiritual advocate, she embarks on a three night journey into terror.', 'genres': ['Horror', 'Thriller'], 'title': 'Death of a Ghost Hunter', 'score': 4.676314353942871}
{'_id': ObjectId('573a1398f29313caabcebf6f'), 'plot': 'After an accident leaves a young man dead, his spirit stays behind to warn his lover of impending danger, with the help of a reluctant psychic.', 'genres': ['Drama', 'Fantasy', 'Romance'], 'title': 'Ghost', 'score': 3.9638845920562744}
{'_id': ObjectId('573a13cdf29313caabd83c08'), 'plot': "A man tries to solve his lover's murder by communicating with her spirit through the help of a medium.", 'genres': ['Drama', 'Fantasy', 'Mystery'], 'title': 'Ghost', 'score': 3.9638845920562744}
{'_id': ObjectId('573a13cef29313caabd873a2'), 'plot': "A man tries to solve his lover's murder by communicating with her spirit through the help of a medium.", 'genres': ['Drama', 'Fantasy', 'Mystery'], 'title': 'Ghost', 'score': 3.9638845920562744}
{'_id': ObjectId('573a13c3f29313caabd6a149'), 'plot': 'What kind of scenes in a horror film scares you the most? When a ghost appears totally unexpectedly? When the main character does not see the ghost sneaking up behind him? When at the very ...', 'genres': ['Horror', 'Thriller'], 'title': 'Coming Soon', 'score': 3.526711940765381}
{'_id': ObjectId('573a1397f29313caabce7ea1'), 'plot': "Four successful elderly gentlemen, members of the Chowder Society, share a gruesome, 50-year old secret. When one of Edward Wanderley's twin sons dies in a bizarre accident, the group ...", 'genres': ['Drama', 'Horror', 'Thriller'], 'title': 'Ghost Story', 'score': 3.3177831172943115}
{'_id': ObjectId('573a13a4f29313caabd117df'), 'plot': 'Stunt motorcyclist Johnny Blaze gives up his soul to become a hellblazing vigilante, to fight against power hungry Blackheart, the son of the devil himself.', 'genres': ['Action', 'Fantasy', 'Thriller'], 'title': 'Ghost Rider', 'score': 3.3177831172943115}
{'_id': ObjectId('573a13a6f29313caabd185dc'), 'plot': 'A salvage crew that discovers a long-lost 1962 passenger ship floating lifeless in a remote region of the Bering Sea soon notices, as they prepare to tow it back to land, that "strange things" happen...', 'genres': ['Horror', 'Mystery'], 'title': 'Ghost Ship', 'score': 3.3177831172943115}

The movie documents in the results contain the query term ghost in the plot or title field and aren't in the Comedy genre. MongoDB Search didn't return documents in the Comedy genre with the term ghost in the plot or title field because those documents didn't rank in the top 10 documents since the query reduced the score of those documents by 50%.

You can normalize your $search query score in the range from 0 to 1 in the subsequent stages of your aggregation pipeline. You can use the following stages after your $search stage in the following order to normalize the score:

  • $addFields

    {
    "$addFields": {
    "score": {
    "$meta": "searchScore"
    }
    }
    }
  • $setWindowFields

    {
    "$setWindowFields": {
    "output": {
    "maxScore": {
    "$max": "$score"
    }
    }
    }
    }
  • $addFields

    {
    "$addFields": {
    "normalizedScore": {
    "$divide": [
    "$score", "$maxScore"
    ]
    }
    }
    }
1db.movies.aggregate([{
2 "$search": {
3 "text": {
4 "query": "Helsinki",
5 "path": "plot"
6 }
7 }
8 },
9 {
10 "$limit": 5
11 },
12 {
13 "$project": {
14 "_id": 0,
15 "title": 1,
16 "score": 1,
17 "maxScore": 1,
18 "normalizedScore": 1
19 }
20 },
21 {
22 "$addFields": {
23 "score": {
24 "$meta": "searchScore"
25 }
26 }
27 },
28 {
29 "$setWindowFields": {
30 "output": {
31 "maxScore": {
32 "$max": "$score"
33 }
34 }
35 }
36 },
37 {
38 "$addFields": {
39 "normalizedScore": {
40 "$divide": [
41 "$score", "$maxScore"
42 ]
43 }
44 }
45}])
1[
2 {
3 title: 'Drifting Clouds',
4 score: 4.5660295486450195,
5 maxScore: 4.5660295486450195,
6 normalizedScore: 1
7 },
8 {
9 title: 'Sairaan kaunis maailma',
10 score: 4.041563034057617,
11 maxScore: 4.5660295486450195,
12 normalizedScore: 0.8851372929150143
13 },
14 {
15 title: 'Bad Luck Love',
16 score: 3.6251673698425293,
17 maxScore: 4.5660295486450195,
18 normalizedScore: 0.79394303764817
19 },
20 {
21 title: 'Bad Luck Love',
22 score: 3.6251673698425293,
23 maxScore: 4.5660295486450195,
24 normalizedScore: 0.79394303764817
25 },
26 {
27 title: 'Forbidden Fruit',
28 score: 3.6251673698425293,
29 maxScore: 4.5660295486450195,
30 normalizedScore: 0.79394303764817
31 }
32]

The MongoDB Search results contain the following scores:

  • The modified score for the $search query in the score field from the $addFields stage.

  • The maximum score assigned to the documents in the results in the maxScore field from the $setWindowFields stage.

  • The normalized score in the normalizedScore field from the $addFields stage. MongoDB computes this score by dividing the modified score in $score by the maximum score in $maxScore using $divide.

To learn more about compound queries using MongoDB Search, take Unit 9 of the Intro To MongoDB Course on MongoDB University. The 1.5-hour unit includes an overview of MongoDB Search. The unit also covers creating MongoDB Search indexes, running $search queries using compound operators, and grouping results using facet (MongoDB Search Operator).