Docs Menu
Docs Home
/
MongoDB Atlas
/ /

Step 2: Run Atlas Search Queries

On this page

  • Procedure
  • Next Steps

➤ Use the Select your language drop-down menu to set the language of the examples on this page.


Important

Feature unavailable in Serverless Instances

Serverless instances don't support this feature at this time. To learn more, see Serverless Instance Limitations.

This part of the tutorial guides you through running Atlas Search queries.

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

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

  3. If it's not already displayed, click Clusters in the sidebar.

    The Clusters page displays.

2

You can go the Atlas Search page from the sidebar, the Data Explorer, or your cluster details page.

  1. In the sidebar, click Atlas Search under the Services heading.

  2. From the Select data source dropdown, select your cluster and click Go to Atlas Search.

    The Atlas Search page displays.

  1. Click the Browse Collections button for your cluster.

  2. Expand the database and select the collection.

  3. Click the Search Indexes tab for the collection.

    The Atlas Search page displays.

  1. Click the cluster's name.

  2. Click the Atlas Search tab.

    The Atlas Search page displays.

3

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

4

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

5

Copy and paste the following query into the Query Editor, and then click the Search button in the Query Editor.

[
{
$search: {
index: "default",
text: {
query: "baseball",
path: "plot"
}
}
}
]
SCORE: 3.8531038761138916 _id: "573a13b3f29313caabd3b409"
fullplot: "Three guys, all their lives, have been living in the shadow of bullies…"
imdb: Object
year: 2006
SCORE: 3.6254453659057617 _id: "573a1399f29313caabcee801"
plot: "A young boy is bequeathed the ownership of a professional baseball tea..."
genres: Array
runtime: 119
SCORE: 3.6254453659057617 _id: "573a139af29313caabcefe18"
plot: "A trained chimpanzee plays third base for a minor-league baseball team..."
genres: Array
runtime: 94
SCORE: 3.489243507385254 _id: "573a1393f29313caabcdca79"
plot: "The story of the life and career of the famed baseball player, Lou Geh..."
genres: Array
runtime: 128
SCORE: 3.489243507385254 _id: "573a1399f29313caabcecef1"
plot: "Babe Ruth becomes a baseball legend but is unheroic to those who know ..."
genres: Array
runtime: 115
SCORE: 3.4249095916748047 _id: "573a1398f29313caabcebccf"
plot: "Two disquieted junior baseball players seek revenge on the local yakuz…"
genres: Array
runtime: 96
SCORE: 3.4249095916748047 _id: "573a13bdf29313caabd5813d"
plot: "Dominican baseball star Miguel "Sugar" Santos is recruited to play in …"
genres: Array
runtime: 114
SCORE: 3.3629050254821777 _id: "573a139af29313caabcefe79"
plot: "An all star baseball player becomes the unhealthy focus of a down on h…"
genres: Array
runtime: 116
SCORE: 3.303105354309082 _id: "573a1399f29313caabced370"
plot: "A fading baseball player is traded to a Japanese team and has trouble …"
genres: Array
runtime: 108
SCORE: 3.303105354309082 _id: "573a13a0f29313caabd05773"
fullplot: "The story of Baseball Hall-of-Famer Hank Greenberg is told through arc…"
imdb: Object
year: 1998

To learn more about the $search pipeline stage, see its reference page. For complete aggregation pipeline documentation, see the MongoDB Server Manual.

6

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 via mongosh.

2

Run the following command at mongosh prompt:

use sample_mflix
3

The following query searches for the word baseball in the plot field. It includes a $limit stage to limit the output to 5 results and a $project stage to exclude all fields except title and plot.

db.movies.aggregate([
{
$search: {
"text": {
"query": "baseball",
"path": "plot"
}
}
},
{
$limit: 5
},
{
$project: {
"_id": 0,
"title": 1,
"plot": 1
}
}
])
{
"plot" : "A trio of guys try and make up for missed
opportunities in childhood by forming a three-player
baseball team to compete against standard children
baseball squads.",
"title" : "The Benchwarmers"
}
{
"plot" : "A young boy is bequeathed the ownership of a
professional baseball team.",
"title" : "Little Big League"
}
{
"plot" : "A trained chimpanzee plays third base for a
minor-league baseball team.",
"title" : "Ed"
}
{
"plot" : "The story of the life and career of the famed
baseball player, Lou Gehrig.",
"title" : "The Pride of the Yankees"
}
{
"plot" : "Babe Ruth becomes a baseball legend but is
unheroic to those who know him.",
"title" : "The Babe"
}

For more information about the $search pipeline stage, see its reference page. For complete aggregation pipeline documentation, see the MongoDB Server Manual.

4

$search has several operators for constructing different types of queries. The following query uses the compound operator to combine several operators into a single query. It has the following search criteria:

  • The plot field must contain either Hawaii or Alaska.

  • The plot field must contain a four-digit number, such as a year.

  • The genres field must not contain either Comedy or Romance.

  • The title field must not contain Beach or Snow.

db.movies.aggregate([
{
$search: {
"compound": {
"must": [ {
"text": {
"query": ["Hawaii", "Alaska"],
"path": "plot"
},
},
{
"regex": {
"query": "([0-9]{4})",
"path": "plot",
"allowAnalyzedField": true
}
} ],
"mustNot": [ {
"text": {
"query": ["Comedy", "Romance"],
"path": "genres"
}
},
{
"text": {
"query": ["Beach", "Snow"],
"path": "title"
}
} ]
}
}
},
{
$project: {
"title": 1,
"plot": 1,
"genres": 1,
"_id": 0
}
}
])
{
"plot" : "A modern aircraft carrier is thrown back in time
to 1941 near Hawaii, just hours before the Japanese attack
on Pearl Harbor.",
"genres" : [ "Action", "Sci-Fi" ],
"title" : "The Final Countdown"
}
{
"plot" : "Follows John McCain's 2008 presidential
campaign, from his selection of Alaska Governor Sarah
Palin as his running mate to their ultimate defeat in the
general election.",
"genres" : [ "Biography", "Drama", "History" ],
"title" : "Game Change"
}
{
"plot" : "A devastating and heartrending take on grizzly
bear activists Timothy Treadwell and Amie Huguenard, who
were killed in October of 2003 while living among
grizzlies in Alaska.",
"genres" : [ "Documentary", "Biography" ],
"title" : "Grizzly Man"
}
{
"plot" : "Truman Korovin is a lonely, sharp-witted cab
driver in Fairbanks, Alaska, 1980. The usual routine of
picking up fares and spending his nights at his favorite
bar, the Boatel, is disrupted ...",
"genres" : [ "Drama" ],
"title" : "Chronic Town"
}
1

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

2

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

3

The following query searches for the word baseball in the plot field. It includes a $limit stage to limit the output to 5 results and a $project stage to exclude all fields except title and plot.

To run this simple Atlas Search 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
    {
    "text": {
    "query": "baseball",
    "path": "plot"
    }
    }
    $limit
    5
    $project
    {
    "_id": 0,
    "title": 1,
    "plot": 1
    }

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

{
"plot" : "A trio of guys try and make up for missed
opportunities in childhood by forming a three-player
baseball team to compete against standard children
baseball squads.",
"title" : "The Benchwarmers"
}
{
"plot" : "A young boy is bequeathed the ownership of a
professional baseball team.",
"title" : "Little Big League"
}
{
"plot" : "A trained chimpanzee plays third base for a
minor-league baseball team.",
"title" : "Ed"
}
{
"plot" : "The story of the life and career of the famed
baseball player, Lou Gehrig.",
"title" : "The Pride of the Yankees"
}
{
"plot" : "Babe Ruth becomes a baseball legend but is
unheroic to those who know him.",
"title" : "The Babe"
}

For more information about the $search pipeline stage, see its reference page. For complete aggregation pipeline documentation, see the MongoDB Server Manual.

4

$search has several operators for constructing different types of queries. The following query uses the compound operator to combine several operators into a single query. It has the following search criteria:

  • The plot field must contain either Hawaii or Alaska.

  • The plot field must contain a four-digit number, such as a year.

  • The genres field must not contain either Comedy or Romance.

  • The title field must not contain Beach or Snow.

To run this complex Atlas Search 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
    {
    "compound": {
    "must": [ {
    "text": {
    "query": ["Hawaii", "Alaska"],
    "path": "plot"
    },
    },
    {
    "regex": {
    "query": "([0-9]{4})",
    "path": "plot",
    "allowAnalyzedField": true
    }
    } ],
    "mustNot": [ {
    "text": {
    "query": ["Comedy", "Romance"],
    "path": "genres"
    }
    },
    {
    "text": {
    "query": ["Beach", "Snow"],
    "path": "title"
    }
    } ]
    }
    }
    $project
    {
    "title": 1,
    "plot": 1,
    "genres": 1,
    "_id": 0
    }

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

{
"plot" : "A modern aircraft carrier is thrown back in time
to 1941 near Hawaii, just hours before the Japanese attack
on Pearl Harbor.",
"genres" : [ "Action", "Sci-Fi" ],
"title" : "The Final Countdown"
}
{
"plot" : "Follows John McCain's 2008 presidential
campaign, from his selection of Alaska Governor Sarah
Palin as his running mate to their ultimate defeat in the
general election.",
"genres" : [ "Biography", "Drama", "History" ],
"title" : "Game Change"
}
{
"plot" : "A devastating and heartrending take on grizzly
bear activists Timothy Treadwell and Amie Huguenard, who
were killed in October of 2003 while living among
grizzlies in Alaska.",
"genres" : [ "Documentary", "Biography" ],
"title" : "Grizzly Man"
}
{
"plot" : "Truman Korovin is a lonely, sharp-witted cab
driver in Fairbanks, Alaska, 1980. The usual routine of
picking up fares and spending his nights at his favorite
bar, the Boatel, is disrupted ...",
"genres" : [ "Drama" ],
"title" : "Chronic Town"
}
1
  1. Create a new directory called simple-query-example and initialize your project with the dotnet new command.

    mkdir simple-query-example
    cd simple-query-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 Atlas cluster.

    • Searches for the word baseball in the plot field. It includes a:

      • $limit stage to limit the output to 5 results

      • $project stage to exclude all fields except title and plot

    • 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 SimpleQuery
    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.Text(movie => movie.Plot, "baseball"))
    25 .Project<MovieDocument>(Builders<MovieDocument>.Projection
    26 .Include(movie => movie.Plot)
    27 .Include(movie => movie.Title)
    28 .Exclude(movie => movie.Id))
    29 .Limit(5)
    30 .ToList();
    31
    32 // print results
    33 foreach (var movie in results)
    34 {
    35 Console.WriteLine(movie.ToJson());
    36 }
    37 }
    38}
    39
    40[BsonIgnoreExtraElements]
    41public class MovieDocument
    42{
    43 [BsonIgnoreIfDefault]
    44 public ObjectId Id { get; set; }
    45 public string Plot { get; set; }
    46 public string Title { get; set; }
    47}
  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 via Drivers.

  5. Compile and run Program.cs file.

    dotnet run simple-query-example.csproj
    {
    "plot" : "A trio of guys try and make up for missed
    opportunities in childhood by forming a three-player
    baseball team to compete against standard children baseball
    squads.",
    "title" : "The Benchwarmers"
    }
    {
    "plot" : "A young boy is bequeathed the ownership of a
    professional baseball team.",
    "title" : "Little Big League"
    }
    {
    "plot" : "A trained chimpanzee plays third base for a
    minor-league baseball team.",
    "title" : "Ed"
    }
    {
    "plot" : "The story of the life and career of the famed
    baseball player, Lou Gehrig.",
    "title" : "The Pride of the Yankees"
    }
    {
    "plot" : "Babe Ruth becomes a baseball legend but is
    unheroic to those who know him.",
    "title" : "The Babe"
    }
2
  1. Create a new directory called complex-query-example and initialize your project with the dotnet new command.

    mkdir complex-query-example
    cd complex-query-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.

    $search has several operators for constructing different types of queries. This code example uses the compound operator to combine several operators into a single query. It has the following search criteria:

    • The plot field must contain either Hawaii or Alaska.

    • The plot field must contain a four-digit number, such as a year.

    • The genres field must not contain either Comedy or Romance.

    • The title field must not contain Beach or Snow.

    1using MongoDB.Bson;
    2using MongoDB.Bson.Serialization.Attributes;
    3using MongoDB.Bson.Serialization.Conventions;
    4using MongoDB.Driver;
    5using MongoDB.Driver.Search;
    6
    7public class ComplexQuery
    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 // declare data for the compound query
    23 string[] terms = { "Hawaii", "Alaska" };
    24 string[] genres = { "Comedy", "Romance" };
    25 string[] titles = { "Beach", "Snow" };
    26
    27 // define and run pipeline
    28 var results = moviesCollection.Aggregate()
    29 .Search(Builders<MovieDocument>.Search.Compound()
    30 .Must(Builders<MovieDocument>.Search.Text(movie => movie.Plot, terms))
    31 .Must(Builders<MovieDocument>.Search.Regex(movie => movie.Plot, "([0-9]{4})", true))
    32 .MustNot((Builders<MovieDocument>.Search.Text(movie => movie.Genres, genres)))
    33 .MustNot((Builders<MovieDocument>.Search.Text(movie => movie.Title, titles))))
    34 .Project<MovieDocument>(Builders<MovieDocument>.Projection
    35 .Include(movie => movie.Genres)
    36 .Include(movie => movie.Plot)
    37 .Include(movie => movie.Title)
    38 .Exclude(movie => movie.Id))
    39 .ToList();
    40
    41 // print results
    42 foreach (var movie in results)
    43 {
    44 Console.WriteLine(movie.ToJson());
    45 }
    46 }
    47}
    48
    49[BsonIgnoreExtraElements]
    50public class MovieDocument
    51{
    52 [BsonIgnoreIfDefault]
    53 public ObjectId Id { get; set; }
    54 public string[] Genres { get; set; }
    55 public string Plot { get; set; }
    56 public string Title { get; set; }
    57}
  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 via Drivers.

  5. Compile and run Program.cs file.

    dotnet run complex-query-example.csproj
    {
    "genres" : ["Action", "Sci-Fi"],
    "plot" : "A modern aircraft carrier is thrown back in time to 1941 near Hawaii, just hours before the Japanese attack on Pearl Harbor.",
    "title" : "The Final Countdown"
    }
    {
    "genres" : ["Biography", "Drama", "History"],
    "plot" : "Follows John McCain's 2008 presidential campaign,
    from his selection of Alaska Governor Sarah Palin as his
    running mate to their ultimate defeat in the general
    election.",
    "title" : "Game Change"
    }
    {
    "genres" : ["Documentary", "Biography"],
    "plot" : "A devastating and heartrending take on grizzly
    bear activists Timothy Treadwell and Amie Huguenard, who
    were killed in October of 2003 while living among grizzlies
    in Alaska.",
    "title" : "Grizzly Man"
    }
    {
    "genres" : ["Drama"],
    "plot" : "Truman Korovin is a lonely, sharp-witted cab
    driver in Fairbanks, Alaska, 1980. The usual routine of
    picking up fares and spending his nights at his favorite
    bar, the Boatel, is disrupted ...",
    "title" : "Chronic Town"
    }
1
  1. Create a file named simple-query.go.

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

    The code example performs the following tasks:

    • Imports mongodb packages and dependencies.

    • Establishes a connection to your Atlas cluster.

    • Searches for the word baseball in the plot field. It includes the following stages:

      • $limit stage to limit the output to 5 results

      • $project stage to exclude all fields except title and plot

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

    1package main
    2import (
    3 "context"
    4 "fmt"
    5 "time"
    6
    7 "go.mongodb.org/mongo-driver/bson"
    8 "go.mongodb.org/mongo-driver/mongo"
    9 "go.mongodb.org/mongo-driver/mongo/options"
    10)
    11// define structure of movies collection
    12type MovieCollection struct {
    13 title string `bson:"Title,omitempty"`
    14 plot string `bson:"Plot,omitempty"`
    15}
    16func main() {
    17 var err error
    18 // connect to the Atlas cluster
    19 ctx := context.Background()
    20 client, err := mongo.Connect(ctx, options.Client().ApplyURI("<connection-string>"))
    21 if err != nil {
    22 panic(err)
    23 }
    24 defer client.Disconnect(ctx)
    25 // set namespace
    26 collection := client.Database("sample_mflix").Collection("movies")
    27 // define pipeline
    28 searchStage := bson.D{{"$search", bson.D{{"text", bson.D{{"path", "plot"},{"query", "baseball"}}}}}}
    29 limitStage := bson.D{{"$limit", 5}}
    30 projectStage := bson.D{{"$project", bson.D{{"title", 1}, {"plot", 1}, {"_id", 0}}}}
    31 // specify the amount of time the operation can run on the server
    32 opts := options.Aggregate().SetMaxTime(5 * time.Second)
    33 // run pipeline
    34 cursor, err := collection.Aggregate(ctx, mongo.Pipeline{searchStage, limitStage, projectStage}, opts)
    35 if err != nil {
    36 panic(err)
    37 }
    38 // print results
    39 var results []bson.D
    40 if err = cursor.All(context.TODO(), &results); err != nil {
    41 panic(err)
    42 }
    43 for _, result := range results {
    44 fmt.Println(result)
    45 }
    46}
  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 via Drivers.

  4. Run the following command to query your collection:

    go run simple-query.go
    [
    {plot A trio of guys try and make up for missed opportunities in childhood by forming a three-player baseball team to compete against standard children baseball squads.}
    {title The Benchwarmers}
    ]
    [
    {plot A young boy is bequeathed the ownership of a professional baseball team.}
    {title Little Big League}
    ]
    [
    {plot A trained chimpanzee plays third base for a minor-league baseball team.}
    {title Ed}
    ]
    [
    {plot The story of the life and career of the famed baseball player, Lou Gehrig.}
    {title The Pride of the Yankees}
    ]
    [
    {plot Babe Ruth becomes a baseball legend but is unheroic to those who know him.}
    {title The Babe}
    ]
2
  1. Create a file named complex-query.go.

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

    $search has several operators for constructing different types of queries. This code example uses the compound operator to combine several operators into a single query. It has the following search criteria:

    • The plot field must contain either Hawaii or Alaska.

    • The plot field must contain a four-digit number, such as a year.

    • The genres field must not contain either Comedy or Romance.

    • The title field must not contain Beach or Snow.

    1package main
    2import (
    3 "context"
    4 "fmt"
    5 "time"
    6
    7 "go.mongodb.org/mongo-driver/bson"
    8 "go.mongodb.org/mongo-driver/mongo"
    9 "go.mongodb.org/mongo-driver/mongo/options"
    10)
    11// define structure of movies collection
    12type MovieCollection struct {
    13 title string `bson:"Title,omitempty"`
    14 plot []string `bson:"Plot,omitempty"`
    15}
    16func main() {
    17 var err error
    18 // connect to the Atlas cluster
    19 ctx := context.Background()
    20 client, err := mongo.Connect(ctx, options.Client().ApplyURI("<connection-string>"))
    21 if err != nil {
    22 panic(err)
    23 }
    24 defer client.Disconnect(ctx)
    25 // set namespace
    26 collection := client.Database("sample_mflix").Collection("movies")
    27 // define pipeline
    28 searchStage := bson.D{{"$search", bson.M{
    29 "compound": bson.M{
    30 "must": bson.A{
    31 bson.M{
    32 "text": bson.D{
    33 {"path", "plot"},{"query", []string{"Hawaii", "Alaska"}},
    34 },
    35 },
    36 bson.M{
    37 "regex": bson.M{
    38 "path": "plot","query": "([0-9]{4})","allowAnalyzedField": true,
    39 },
    40 },
    41 },
    42 "mustNot": bson.A{
    43 bson.D{
    44 {"text", bson.M{
    45 "path": "genres","query": []string{"Comedy", "Romance"},
    46 }},
    47 {"text", bson.M{
    48 "path": "title","query": []string{"Beach", "Snow"},
    49 }},
    50 },
    51 },
    52 },
    53 }}}
    54 projectStage := bson.D{{"$project", bson.D{{"title", 1}, {"plot", 1}, {"genres", 1}, {"_id", 0}}}}
    55 // specify the amount of time the operation can run on the server
    56 opts := options.Aggregate().SetMaxTime(5 * time.Second)
    57 // run pipeline
    58 cursor, err := collection.Aggregate(ctx, mongo.Pipeline{searchStage, projectStage}, opts)
    59 if err != nil {
    60 panic(err)
    61 }
    62 // print results
    63 var results []bson.D
    64 if err = cursor.All(context.TODO(), &results); err != nil {
    65 panic(err)
    66 }
    67 for _, result := range results {
    68 fmt.Println(result)
    69 }
    70}
  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 via Drivers.

  4. Run the following command to query your collection:

    go run complex-query.go
    [
    {plot A modern aircraft carrier is thrown back in time to 1941 near Hawaii, just hours before the Japanese attack on Pearl Harbor.}
    {genres [Action Sci-Fi]}
    {title The Final Countdown}
    ]
    [
    {plot Follows John McCain's 2008 presidential campaign, from his selection of Alaska Governor Sarah Palin as his running mate to their ultimate defeat in the general election.}
    {genres [Biography Drama History]}
    {title Game Change}
    ]
    [
    {plot A devastating and heartrending take on grizzly bear activists Timothy Treadwell and Amie Huguenard, who were killed in October of 2003 while living among grizzlies in Alaska.}
    {genres [Documentary Biography]}
    {title Grizzly Man}
    ]
    [
    {plot Truman Korovin is a lonely, sharp-witted cab driver in Fairbanks, Alaska, 1980. The usual routine of picking up fares and spending his nights at his favorite bar, the Boatel, is disrupted ...}
    {genres [Drama]}
    {title Chronic Town}
    ]
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 SimpleQuery.java.

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

    The code example performs the following tasks:

    • Imports mongodb packages and dependencies.

    • Establishes a connection to your Atlas cluster.

    • Searches for the word baseball in the plot field. It includes a:

      • $limit stage to limit the output to 5 results

      • $project stage to exclude all fields except title and plot

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

    1import java.util.Arrays;
    2import static com.mongodb.client.model.Filters.eq;
    3import static com.mongodb.client.model.Aggregates.limit;
    4import static com.mongodb.client.model.Aggregates.project;
    5import static com.mongodb.client.model.Projections.excludeId;
    6import static com.mongodb.client.model.Projections.fields;
    7import static com.mongodb.client.model.Projections.include;
    8import com.mongodb.client.MongoClient;
    9import com.mongodb.client.MongoClients;
    10import com.mongodb.client.MongoCollection;
    11import com.mongodb.client.MongoDatabase;
    12import org.bson.Document;
    13
    14public class SimpleQuery {
    15 public static void main( String[] args ) {
    16 Document agg = new Document("query", "baseball").append("path","plot");
    17
    18 String uri = "<connection-string>";
    19
    20 try (MongoClient mongoClient = MongoClients.create(uri)) {
    21 MongoDatabase database = mongoClient.getDatabase("sample_mflix");
    22 MongoCollection<Document> collection = database.getCollection("movies");
    23
    24 collection.aggregate(Arrays.asList(
    25 eq("$search", eq("text", agg)),
    26 limit(5),
    27 project(fields(excludeId(), include("title", "plot"))))
    28 ).forEach(doc -> System.out.println(doc.toJson()));
    29 }
    30 }
    31}
  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 via Drivers.

  4. Compile and run SimpleQuery.java file.

    javac SimpleQuery.java
    java SimpleQuery
    {
    "plot": "A trio of guys try and make up for missed opportunities in childhood by forming a three-player baseball team to compete against standard children baseball squads.",
    "title": "The Benchwarmers"
    }
    {
    "plot": "A young boy is bequeathed the ownership of a professional baseball team.",
    "title": "Little Big League"
    }
    {
    "plot": "A trained chimpanzee plays third base for a minor-league baseball team.",
    "title": "Ed"
    }
    {
    "plot": "The story of the life and career of the famed baseball player, Lou Gehrig.",
    "title": "The Pride of the Yankees"
    }
    {
    "plot": "Babe Ruth becomes a baseball legend but is unheroic to those who know him.",
    "title": "The Babe"
    }
3
  1. Create a file named ComplexQuery.java.

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

    $search has several operators for constructing different types of queries. This code example uses the compound operator to combine several operators into a single query. It has the following search criteria:

    • The plot field must contain either Hawaii or Alaska.

    • The plot field must contain a four-digit number, such as a year.

    • The genres field must not contain either Comedy or Romance.

    • The title field must not contain Beach or Snow.

    1import java.util.Arrays;
    2import static com.mongodb.client.model.Filters.eq;
    3import static com.mongodb.client.model.Aggregates.project;
    4import static com.mongodb.client.model.Projections.excludeId;
    5import static com.mongodb.client.model.Projections.fields;
    6import static com.mongodb.client.model.Projections.include;
    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 ComplexQuery {
    14 public static void main( String[] args ) {
    15 Document agg = new Document("must", Arrays.asList(
    16 new Document("text", new Document("query", Arrays.asList("Hawaii", "Alaska")).append("path", "plot")),
    17 new Document("regex", new Document("query", "([0-9]{4})").append("path", "plot").append("allowAnalyzedField", true))))
    18 .append("mustNot", Arrays.asList(
    19 new Document("text", new Document("query", Arrays.asList("Comedy", "Romance")).append("path", "genres")),
    20 new Document("text", new Document("query", Arrays.asList("Beach", "Snow")).append("path", "title"))));
    21
    22 String uri = "<connection-string>";
    23
    24 try (MongoClient mongoClient = MongoClients.create(uri)) {
    25 MongoDatabase database = mongoClient.getDatabase("sample_mflix");
    26 MongoCollection<Document> collection = database.getCollection("movies");
    27
    28 collection.aggregate(Arrays.asList(
    29 eq("$search", eq("compound", agg)),
    30 project(fields(excludeId(), include("title", "plot", "genres"))))
    31 ).forEach(doc -> System.out.println(doc.toJson()));
    32 }
    33 }
    34}
  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 via Drivers.

  4. Compile and run ComplexQuery.java file.

    javac ComplexQuery.java
    java ComplexQuery
    {
    "plot": "A modern aircraft carrier is thrown back in time to 1941 near Hawaii, just hours before the Japanese attack on Pearl Harbor.",
    "genres": ["Action", "Sci-Fi"],
    "title": "The Final Countdown"
    }
    {
    "plot": "Follows John McCain's 2008 presidential campaign, from his selection of Alaska Governor Sarah Palin as his running mate to their ultimate defeat in the general election.",
    "genres": ["Biography", "Drama", "History"],
    "title": "Game Change"
    }
    {
    "plot": "A devastating and heartrending take on grizzly bear activists Timothy Treadwell and Amie Huguenard, who were killed in October of 2003 while living among grizzlies in Alaska.",
    "genres": ["Documentary", "Biography"],
    "title": "Grizzly Man"
    }
    {
    "plot": "Truman Korovin is a lonely, sharp-witted cab driver in Fairbanks, Alaska, 1980. The usual routine of picking up fares and spending his nights at his favorite bar, the Boatel, is disrupted ...",
    "genres": ["Drama"],
    "title": "Chronic Town"
    }
1
mongodb-driver-kotlin-coroutine
4.10.0 or higher version
2
  1. Create a file named SimpleQuery.kt.

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

    The code example performs the following tasks:

    • Imports mongodb packages and dependencies.

    • Establishes a connection to your Atlas cluster.

    • Searches for the word baseball in the plot field. It includes a:

      • $limit stage to limit the output to 5 results

      • $project stage to exclude all fields except title and plot

    • 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.Filters.eq
    4import com.mongodb.client.model.Projections.*
    5import com.mongodb.kotlin.client.coroutine.MongoClient
    6import kotlinx.coroutines.runBlocking
    7import org.bson.Document
    8
    9fun main() {
    10 // establish connection and set namespace
    11 val uri = "<connection-string>"
    12 val mongoClient = MongoClient.create(uri)
    13 val database = mongoClient.getDatabase("sample_mflix")
    14 val collection = database.getCollection<Document>("movies")
    15
    16 runBlocking {
    17 // define query
    18 val agg = Document("query", "baseball").append("path","plot")
    19
    20 // run query and print results
    21 val resultsFlow = collection.aggregate<Document>(
    22 listOf(
    23 eq("\$search", eq("text", agg)),
    24 limit(5),
    25 project(fields(excludeId(), include("title", "plot")))
    26 )
    27 )
    28 resultsFlow.collect { println(it) }
    29 }
    30 mongoClient.close()
    31}
  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 via Drivers.

  4. Run the SimpleQuery.kt file.

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

    Document{{plot=A trio of guys try and make up for missed opportunities in childhood by forming a three-player baseball team to compete against standard children baseball squads., title=The Benchwarmers}}
    Document{{plot=A young boy is bequeathed the ownership of a professional baseball team., title=Little Big League}}
    Document{{plot=A trained chimpanzee plays third base for a minor-league baseball team., title=Ed}}
    Document{{plot=Babe Ruth becomes a baseball legend but is unheroic to those who know him., title=The Babe}}
    Document{{plot=The story of the life and career of the famed baseball player, Lou Gehrig., title=The Pride of the Yankees}}
3
  1. Create a file named ComplexQuery.kt.

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

    $search has several operators for constructing different types of queries. This code example uses the compound operator to combine several operators into a single query. It has the following search criteria:

    • The plot field must contain either Hawaii or Alaska.

    • The plot field must contain a four-digit number, such as a year.

    • The genres field must not contain either Comedy or Romance.

    • The title field must not contain Beach or Snow.

    1import com.mongodb.client.model.Aggregates.limit
    2import com.mongodb.client.model.Aggregates.project
    3import com.mongodb.client.model.Filters.eq
    4import com.mongodb.client.model.Projections.*
    5import com.mongodb.kotlin.client.coroutine.MongoClient
    6import kotlinx.coroutines.runBlocking
    7import org.bson.Document
    8
    9fun main() {
    10 // establish connection and set namespace
    11 val uri = "<connection-string>"
    12 val mongoClient = MongoClient.create(uri)
    13 val database = mongoClient.getDatabase("sample_mflix")
    14 val collection = database.getCollection<Document>("movies")
    15
    16 runBlocking {
    17 // define query
    18 val agg = Document(
    19 "must", listOf(
    20 Document("text", Document("query", listOf("Hawaii", "Alaska"))
    21 .append("path", "plot")),
    22 Document(
    23 "regex",
    24 Document("query", "([0-9]{4})")
    25 .append("path", "plot")
    26 .append("allowAnalyzedField", true)
    27 )
    28 )
    29 )
    30 .append(
    31 "mustNot", listOf(
    32 Document("text", Document("query", listOf("Comedy", "Romance"))
    33 .append("path", "genres")),
    34 Document("text", Document("query", listOf("Beach", "Snow"))
    35 .append("path", "title"))
    36 )
    37 )
    38
    39 // run query and print results
    40 val resultsFlow = collection.aggregate<Document>(
    41 listOf(
    42 eq("\$search", eq("compound", agg)),
    43 project(fields(
    44 excludeId(),
    45 include("title", "plot", "genres")
    46 ))
    47 )
    48 )
    49 resultsFlow.collect { println(it) }
    50 }
    51 mongoClient.close()
    52}
  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 via Drivers.

  4. Run the ComplexQuery.kt file.

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

    Document{{plot=A modern aircraft carrier is thrown back in time to 1941 near Hawaii, just hours before the Japanese attack on Pearl Harbor., genres=[Action, Sci-Fi], title=The Final Countdown}}
    Document{{plot=Follows John McCain's 2008 presidential campaign, from his selection of Alaska Governor Sarah Palin as his running mate to their ultimate defeat in the general election., genres=[Biography, Drama, History], title=Game Change}}
    Document{{plot=A devastating and heartrending take on grizzly bear activists Timothy Treadwell and Amie Huguenard, who were killed in October of 2003 while living among grizzlies in Alaska., genres=[Documentary, Biography], title=Grizzly Man}}
    Document{{plot=Truman Korovin is a lonely, sharp-witted cab driver in Fairbanks, Alaska, 1980. The usual routine of picking up fares and spending his nights at his favorite bar, the Boatel, is disrupted ..., genres=[Drama], title=Chronic Town}}
1
  1. Create a file named simple-query.js.

  2. Copy and paste the code example into the simple-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 Atlas cluster.

    • Searches for the word baseball in the plot field. It includes a $limit stage to limit the output to 5 results and a $project stage to exclude all fields except title and plot.

    • 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 text: {
    8 query: "baseball",
    9 path: "plot",
    10 },
    11 },
    12 },
    13 {
    14 $limit: 5,
    15 },
    16 {
    17 $project: {
    18 _id: 0,
    19 title: 1,
    20 plot: 1,
    21 },
    22 },
    23];
    24
    25MongoClient.connect(
    26 "<connection-string>",
    27 { useNewUrlParser: true, useUnifiedTopology: true },
    28 async function (connectErr, client) {
    29 assert.equal(null, connectErr);
    30 const coll = client.db("sample_mflix").collection("movies");
    31 let cursor = await coll.aggregate(agg);
    32 await cursor.forEach((doc) => console.log(doc));
    33 client.close();
    34 }
    35);
  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 via Drivers.

  4. Run the following command to query your collection:

    node simple-query.js
    {
    plot: 'A trio of guys try and make up for missed opportunities in childhood by forming a three-player baseball team to compete against standard children baseball squads.',
    title: 'The Benchwarmers'
    }
    {
    plot: 'A young boy is bequeathed the ownership of a professional baseball team.',
    title: 'Little Big League'
    }
    {
    plot: 'A trained chimpanzee plays third base for a minor-league baseball team.',
    title: 'Ed'
    }
    {
    plot: 'The story of the life and career of the famed baseball player, Lou Gehrig.',
    title: 'The Pride of the Yankees'
    }
    {
    plot: 'Babe Ruth becomes a baseball legend but is unheroic to those who know him.',
    title: 'The Babe'
    }
2
  1. Create a file named complex-query.js.

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

    $search has several operators for constructing different types of queries. The code example uses the compound operator to combine several operators into a single query. It has the following search criteria:

    • The plot field must contain either Hawaii or Alaska.

    • The plot field must contain a four-digit number, such as a year.

    • The genres field must not contain either Comedy or Romance.

    • The title field must not contain Beach or Snow.

    1const MongoClient = require("mongodb").MongoClient;
    2const assert = require("assert");
    3
    4const agg = [
    5 {
    6 $search: {
    7 compound: {
    8 must: [
    9 {
    10 text: {
    11 query: ["Hawaii", "Alaska"],
    12 path: "plot",
    13 },
    14 },
    15 {
    16 regex: {
    17 query: "([0-9]{4})",
    18 path: "plot",
    19 allowAnalyzedField: true,
    20 },
    21 },
    22 ],
    23 mustNot: [
    24 {
    25 text: {
    26 query: ["Comedy", "Romance"],
    27 path: "genres",
    28 },
    29 },
    30 {
    31 text: {
    32 query: ["Beach", "Snow"],
    33 path: "title",
    34 },
    35 },
    36 ],
    37 },
    38 },
    39 },
    40 {
    41 $project: {
    42 title: 1,
    43 plot: 1,
    44 genres: 1,
    45 _id: 0,
    46 },
    47 },
    48];
    49
    50MongoClient.connect(
    51 "<connection-string>",
    52 { useNewUrlParser: true, useUnifiedTopology: true },
    53 async function (connectErr, client) {
    54 assert.equal(null, connectErr);
    55 const coll = client.db("sample_mflix").collection("movies");
    56 let cursor = await coll.aggregate(agg);
    57 await cursor.forEach((doc) => console.log(doc));
    58 client.close();
    59 }
    60);
  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.

  4. Run the following command to query your collection:

    node complex-query.js
    {
    plot: 'A modern aircraft carrier is thrown back in time to 1941 near Hawaii, just hours before the Japanese attack on Pearl Harbor.',
    genres: [ 'Action', 'Sci-Fi' ],
    title: 'The Final Countdown'
    }
    {
    plot: "Follows John McCain's 2008 presidential campaign, from his selection of Alaska Governor Sarah Palin as his running mate to their ultimate defeat in the general election.",
    genres: [ 'Biography', 'Drama', 'History' ],
    title: 'Game Change'
    }
    {
    plot: 'A devastating and heartrending take on grizzly bear activists Timothy Treadwell and Amie Huguenard, who were killed in October of 2003 while living among grizzlies in Alaska.',
    genres: [ 'Documentary', 'Biography' ],
    title: 'Grizzly Man'
    }
    {
    plot: 'Truman Korovin is a lonely, sharp-witted cab driver in Fairbanks, Alaska, 1980. The usual routine of picking up fares and spending his nights at his favorite bar, the Boatel, is disrupted ...',
    genres: [ 'Drama' ],
    title: 'Chronic Town'
    }
1
  1. Create a file named simple-query.py.

  2. Copy and paste the code example into the simple-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 Atlas cluster.

    • Searches for the word baseball in the plot field. It includes a $limit stage to limit the output to 5 results and a $project stage to exclude all fields except title and plot.

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

    1import pymongo
    2import dns
    3
    4client = pymongo.MongoClient('<connection-string>')
    5result = client['sample_mflix']['movies'].aggregate([
    6 {
    7 '$search': {
    8 'index': 'default',
    9 'text': {
    10 'query': 'baseball',
    11 'path': 'plot'
    12 }
    13 }
    14 }, {
    15 '$limit': 5
    16 }, {
    17 '$project': {
    18 '_id': 0,
    19 'title': 1,
    20 'plot': 1
    21 }
    22 }
    23])
    24
    25for i in result:
    26 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 via Drivers.

  4. Run the following command to query your collection:

    python simple-query.py
    {'plot': 'A trio of guys try and make up for missed opportunities in childhood by forming a three-player baseball team to compete against standard children baseball squads.', 'title': 'The Benchwarmers'}
    {'plot': 'A young boy is bequeathed the ownership of a professional baseball team.', 'title': 'Little Big League'}
    {'plot': 'A trained chimpanzee plays third base for a minor-league baseball team.', 'title': 'Ed'}
    {'plot': 'The story of the life and career of the famed baseball player, Lou Gehrig.', 'title': 'The Pride of the Yankees'}
    {'plot': 'Babe Ruth becomes a baseball legend but is unheroic to those who know him.', 'title': 'The Babe'}
2
  1. Create a file named complex-query.py.

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

    $search has several operators for constructing different types of queries. The following query uses the compound operator to combine several operators into a single query. It has the following search criteria:

    • The plot field must contain either Hawaii or Alaska.

    • The plot field must contain a four-digit number, such as a year.

    • The genres field must not contain either Comedy or Romance.

    • The title field must not contain Beach or Snow.

    1import pymongo
    2import dns
    3
    4client = pymongo.MongoClient('<connection-string>')
    5result = client['sample_mflix']['movies'].aggregate([
    6 {
    7 '$search': {
    8 'compound': {
    9 'must': [
    10 {
    11 'text': {
    12 'query': [
    13 'Hawaii', 'Alaska'
    14 ],
    15 'path': 'plot'
    16 }
    17 }, {
    18 'regex': {
    19 'query': '([0-9]{4})',
    20 'path': 'plot',
    21 'allowAnalyzedField': True
    22 }
    23 }
    24 ],
    25 'mustNot': [
    26 {
    27 'text': {
    28 'query': [
    29 'Comedy', 'Romance'
    30 ],
    31 'path': 'genres'
    32 }
    33 }, {
    34 'text': {
    35 'query': [
    36 'Beach', 'Snow'
    37 ],
    38 'path': 'title'
    39 }
    40 }
    41 ]
    42 }
    43 }
    44 }, {
    45 '$project': {
    46 'title': 1,
    47 'plot': 1,
    48 'genres': 1,
    49 '_id': 0
    50 }
    51 }
    52])
    53
    54for i in result:
    55 print(i)
  3. Run the following command to query your collection:

    python complex-query.py
    {'plot': 'A modern aircraft carrier is thrown back in time to 1941 near Hawaii, just hours before the Japanese attack on Pearl Harbor.', 'genres': ['Action', 'Sci-Fi'], 'title': 'The Final Countdown'}
    {'plot': "Follows John McCain's 2008 presidential campaign, from his selection of Alaska Governor Sarah Palin as his running mate to their ultimate defeat in the general election.", 'genres': ['Biography', 'Drama', 'History'], 'title': 'Game Change'}
    {'plot': 'A devastating and heartrending take on grizzly bear activists Timothy Treadwell and Amie Huguenard, who were killed in October of 2003 while living among grizzlies in Alaska.', 'genres': ['Documentary', 'Biography'], 'title': 'Grizzly Man'}
    {'plot': 'Truman Korovin is a lonely, sharp-witted cab driver in Fairbanks, Alaska, 1980. The usual routine of picking up fares and spending his nights at his favorite bar, the Boatel, is disrupted ...', 'genres': ['Drama'], 'title': 'Chronic Town'}

Now that you ran some queries, review the Atlas Search documentation to learn more about the different operators and other queries you can run. More query examples are available througout the Atlas Search documentation.

Prefer to learn by watching?

Follow along with this video tutorial walk-through that demonstrates how to build Atlas Search queries for a Restaurant Finder demo application, which is also available at www.atlassearchrestaurants.com.

Duration: 20 Minutes

Back

1: Create a Search Index