Docs Menu
Docs Home
/
Atlas
/

Atlas Search Quick Start

Atlas Search is an embedded full-text search in MongoDB Atlas that gives you a seamless, scalable experience for building relevance-based app features. This quick start describes how to get started in the following steps:

  1. Create an Atlas Search index on a sample collection.

  2. Build an Atlas Search query to search the collection. You will learn how to:

    • Run a basic query to search for a term in a field

    • Use an operator to refine your search

    • Add a search option to process your results

Time required: 15 minutes

Note

This tutorial includes examples for a selection of clients. For all supported clients, see the Indexes and Queries pages.

In this section, you create an Atlas Search index on the sample movies collection. You can create the Atlas Search index in either an Atlas cluster or a deployment hosted on your local computer.

1
  1. Create a free Atlas account or sign in to an existing account.

  2. If you don't yet have an Atlas cluster, create a free M0 cluster. To learn more about creating an Atlas cluster, see Create a Cluster.

    You can create only one M0 Free cluster per project.

  3. If you haven't yet loaded the sample dataset for this quick start onto your cluster, load the sample_mflix sample database onto your cluster.

    If you already loaded the sample_mflix dataset, check that the sample_mflix database contains the embedded_movies collection. If it doesn't, drop the sample_mflix database and reload the sample_mflix dataset.

    Loading the sample dataset can take several minutes to complete.

  4. In the left sidebar, click Atlas Search. Choose your cluster from the Select data source menu and click Go to Atlas Search.

2

➤ Use the Select your language drop-down menu to set the client for this tutorial.


  1. When the sample data finishes loading, click Create Search Index.

  2. Make the following selections on the page and then click Next.

    Search Type

    Select the Atlas Search index type.

    Index Name and Data Source

    Specify the following information:

    • Index Name: default

    • Database and Collection:

      • sample_mflix

      • movies

    Configuration Method

    For a guided experience, select Visual Editor.

    To edit the raw index definition, select JSON Editor.
  3. Define the index.

    The following index definition dynamically indexes the fields in the movies collection.

    Review the "default" index definition for the movies collection.

    1. Review the index definition.

      Your index definition should look similar to the following:

      {
      "mappings": {
      "dynamic": true
      }
      }

      The above index definition dynamically indexes the fields of supported types in each document in the movies collection.

    2. Click Next.

  4. Click Create Search Index.

  5. Wait for the index to finish building.

    The index should take about one minute to build. While it is building, the Status column reads Build in Progress. When it is finished building, the Status column reads Active.

  1. Connect to the Atlas cluster using mongosh.

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

  2. Switch to the database that contains the collection for which you want to create the index.

    Example

    use sample_mflix
    switched to db sample_mflix
  3. Run the db.collection.createSearchIndex() method to create the index.

    db.movies.createSearchIndex(
    "default",
    { mappings: { dynamic: true } }
    )
    default
1

Open Compass and connect to your Atlas cluster. For detailed instructions, see Connect via Compass.

2

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

3
  1. Click the Indexes tab, then select Search Indexes.

  2. Click Create Index to open the index creation dialog box.

  3. Specify a name for the index.

    Your Atlas Search index is named default by default. If you keep this name, then your index will be the default Search index for any Atlas Search query that does not specify a different index option in its operators. If you are creating multiple indexes, we recommend that you maintain a consistent, descriptive naming convention across your indexes.

  4. Specify the JSON Atlas Search index definition.

    1{
    2 "analyzer": "<analyzer-for-index>",
    3 "searchAnalyzer": "<analyzer-for-query>",
    4 "mappings": {
    5 "dynamic": <boolean>,
    6 "fields": { <field-definition> }
    7 },
    8 "numPartitions": <integer>,
    9 "analyzers": [ <custom-analyzer> ],
    10 "storedSource": <boolean> | {
    11 <stored-source-definition>
    12 },
    13 "synonyms": [
    14 {
    15 <synonym-mapping-definition>
    16 }
    17 ]
    18}
    19
  5. Click Create Search Index.

  1. Set up and initialize the .NET/C# project.

    # Create a new directory and initialize the project
    mkdir atlas-search-quickstart && cd atlas-search-quickstart
    dotnet new console
    # Add the MongoDB .NET/C# Driver to your project
    dotnet add package MongoDB.Driver

    For more detailed installation instructions, see the MongoDB C# Driver documentation.

  2. Define the index.

    Paste the following code into the Program.cs file.

    Program.cs
    1using MongoDB.Bson;
    2using MongoDB.Driver;
    3
    4// connect to your Atlas deployment
    5var uri = "<connection-string>";
    6
    7var client = new MongoClient(uri);
    8
    9var db = client.GetDatabase("sample_mflix");
    10var collection = db.GetCollection<BsonDocument>("movies");
    11
    12// define your Atlas Search index
    13var index = new CreateSearchIndexModel(
    14 "default", new BsonDocument
    15 {
    16 { "mappings", new BsonDocument
    17 {
    18 { "dynamic", true }
    19 }
    20 }
    21 });
    22
    23var result = collection.SearchIndexes.CreateOne(index);
    24Console.WriteLine(result);

    Your connection string should use the following format:

    mongodb+srv://<db_username>:<db_password>@<clusterName>.<hostname>.mongodb.net

    Note

    Ensure that your connection string includes your database user's credentials. To learn more about finding your connection string, see Connect via Drivers.

    Your connection string should use the following format:

    mongodb://localhost:<port-number>/?directConnection=true
  3. Create the index.

    dotnet run Program.cs
    default
  1. Set up and initialize the Go module.

    # Create a new directory and initialize the project
    mkdir atlas-search-quickstart && cd atlas-search-quickstart
    go mod init atlas-search-quickstart
    # Add the MongoDB Go Driver to your project
    go get go.mongodb.org/mongo-driver/v2/mongo

    For more detailed installation instructions, see the MongoDB Go Driver documentation.

  2. Define the index.

    Paste the following code into a file named create-index.go.

    create-index.go
    1package main
    2
    3import (
    4 "context"
    5 "log"
    6
    7 "go.mongodb.org/mongo-driver/v2/bson"
    8 "go.mongodb.org/mongo-driver/v2/mongo"
    9 "go.mongodb.org/mongo-driver/v2/mongo/options"
    10)
    11
    12func main() {
    13 ctx := context.Background()
    14
    15 // Replace the placeholder with your Atlas connection string
    16 const uri = "<connection-string>"
    17
    18 // Connect to your Atlas cluster
    19 clientOptions := options.Client().ApplyURI(uri)
    20 client, err := mongo.Connect(clientOptions)
    21 if err != nil {
    22 log.Fatalf("failed to connect to the server: %v", err)
    23 }
    24 defer func() { _ = client.Disconnect(ctx) }()
    25
    26 // Set the namespace
    27 coll := client.Database("sample_mflix").Collection("movies")
    28
    29 // Define a simple Atlas Search index
    30 indexName := "default"
    31
    32 // Create the default definition for search index
    33 definition := bson.D{{"mappings", bson.D{{"dynamic", true}}}}
    34 indexModel := mongo.SearchIndexModel{
    35 Definition: definition,
    36 Options: options.SearchIndexes().SetName(indexName),
    37 }
    38
    39 // Create the index
    40 searchIndexName, err := coll.SearchIndexes().CreateOne(ctx, indexModel)
    41 if err != nil {
    42 log.Fatalf("failed to create the search index: %v", err)
    43 }
    44 log.Println("New search index named " + searchIndexName + " is building.")
    45}

    Your connection string should use the following format:

    mongodb+srv://<db_username>:<db_password>@<clusterName>.<hostname>.mongodb.net

    Note

    Ensure that your connection string includes your database user's credentials. To learn more about finding your connection string, see Connect via Drivers.

    Your connection string should use the following format:

    mongodb://localhost:<port-number>/?directConnection=true
  3. Create the index.

    go run create-index.go
  1. Add the Java driver version 4.11 or higher as a dependency in your Java project. Select one of the following tabs, depending on your package manager:

    If you are using Maven, add the following dependencies to the dependencies array in your project's pom.xml file:

    pom.xml
    <dependencies>
    <!-- MongoDB Java Sync Driver v4.11.0 or later -->
    <dependency>
    <groupId>org.mongodb</groupId>
    <artifactId>mongodb-driver-sync</artifactId>
    <version>[4.11.0,)</version>
    </dependency>
    </dependencies>

    If you are using Gradle, add the following to the dependencies array in your project's build.gradle file:

    build.gradle
    dependencies {
    // MongoDB Java Sync Driver v4.11.0 or later
    implementation 'org.mongodb:mongodb-driver-sync:[4.11.0,)'
    }
  2. Run your package manager to install the dependencies to your project.

    For more detailed installation instructions and version compatibility, see the MongoDB Java Driver documentation.

  3. Define the index.

    Paste the following example into a file named CreateIndex.java.

    CreateIndex.java
    1import com.mongodb.client.MongoClient;
    2import com.mongodb.client.MongoClients;
    3import com.mongodb.client.MongoCollection;
    4import com.mongodb.client.MongoDatabase;
    5import org.bson.Document;
    6
    7public class CreateIndex {
    8 public static void main(String[] args) {
    9 // connect to your Atlas cluster
    10 String uri = "<connection-string>";
    11
    12 try (MongoClient mongoClient = MongoClients.create(uri)) {
    13 // set namespace
    14 MongoDatabase database = mongoClient.getDatabase("sample_mflix");
    15 MongoCollection<Document> collection = database.getCollection("movies");
    16
    17 Document index = new Document("mappings",
    18 new Document("dynamic", true));
    19 collection.createSearchIndex(index);
    20 }
    21 }
    22}

    Your connection string should use the following format:

    mongodb+srv://<db_username>:<db_password>@<clusterName>.<hostname>.mongodb.net

    Note

    Ensure that your connection string includes your database user's credentials. To learn more about finding your connection string, see Connect via Drivers.

    Your connection string should use the following format:

    mongodb://localhost:<port-number>/?directConnection=true
  1. Install the MongoDB Kotlin Coroutine Driver.

    Create a new Kotlin project and install the MongoDB Kotlin Coroutine Driver documentation.

  2. Define the index.

    Create a file named CreateIndex.kt. Copy and paste the following code into the file.

    CreateIndex.kt
    1import com.mongodb.MongoException
    2import com.mongodb.client.model.SearchIndexModel
    3import com.mongodb.client.model.SearchIndexType
    4import com.mongodb.kotlin.client.coroutine.MongoClient
    5import kotlinx.coroutines.runBlocking
    6import org.bson.Document
    7
    8fun main() {
    9 // Replace the placeholder with your MongoDB deployment's connection string
    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 val searchIdx = Document(
    15 "mappings",
    16 Document("dynamic", true)
    17 )
    18 runBlocking {
    19 try {
    20 val result = collection.createSearchIndex("default", searchIdx)
    21 println("Index created: $result")
    22 } catch (e: MongoException) {
    23 println("Failed to create search index: ${e.message}")
    24 } finally {
    25 mongoClient.close()
    26 }
    27 }
    28}

    Your connection string should use the following format:

    mongodb+srv://<db_username>:<db_password>@<clusterName>.<hostname>.mongodb.net

    Note

    Ensure that your connection string includes your database user's credentials. To learn more about finding your connection string, see Connect via Drivers.

    Your connection string should use the following format:

    mongodb://localhost:<port-number>/?directConnection=true
  3. Run the CreateIndex.kt file in your IDE.

  1. Initialize your Node.js project.

    # Create a new directory and initialize the project
    mkdir atlas-search-quickstart && cd atlas-search-quickstart
    npm init -y
    # Add the MongoDB Node.js Driver to your project
    npm install mongodb

    For detailed installation instructions, see the MongoDB Node Driver documentation.

  2. Define the index.

    Paste the following code into a file named create-index.js.

    create-index.js
    1const { MongoClient } = require("mongodb");
    2
    3// connect to your Atlas deployment
    4const uri =
    5 "<connection-string>";
    6
    7const client = new MongoClient(uri);
    8
    9async function run() {
    10 try {
    11
    12 // set namespace
    13 const database = client.db("sample_mflix");
    14 const collection = database.collection("movies");
    15
    16 // define your Atlas Search index
    17 const index = {
    18 name: "default",
    19 definition: {
    20 /* search index definition fields */
    21 "mappings": {
    22 "dynamic": true
    23 }
    24 }
    25 }
    26
    27 // run the helper method
    28 const result = await collection.createSearchIndex(index);
    29 console.log(result);
    30 } finally {
    31 await client.close();
    32 }
    33}
    34
    35run().catch(console.dir);

    Your connection string should use the following format:

    mongodb+srv://<db_username>:<db_password>@<clusterName>.<hostname>.mongodb.net

    Note

    Ensure that your connection string includes your database user's credentials. To learn more about finding your connection string, see Connect via Drivers.

    Your connection string should use the following format:

    mongodb://localhost:<port-number>/?directConnection=true
  3. Create the index.

    node create-index.js
    default
  1. Install the MongoDB Python Driver.

    pip install pymongo

    For detailed installation instructions, see MongoDB Python Driver (PyMongo).

  2. Define the index.

    Paste the following code into a file named create_index.py.

    create_index.py
    1from pymongo import MongoClient
    2from pymongo.operations import SearchIndexModel
    3
    4# connect to your Atlas deployment
    5uri = "<connection-string>"
    6client = MongoClient(uri)
    7
    8# set namespace
    9database = client["sample_mflix"]
    10collection = database["movies"]
    11
    12# define your Atlas Search index
    13search_index_model = SearchIndexModel(
    14 definition={
    15 "mappings": {
    16 "dynamic": True
    17 },
    18 },
    19 name="default",
    20)
    21
    22# create the index
    23result = collection.create_search_index(model=search_index_model)
    24print(result)

    Your connection string should use the following format:

    mongodb+srv://<db_username>:<db_password>@<clusterName>.<hostname>.mongodb.net

    Note

    Ensure that your connection string includes your database user's credentials. To learn more about finding your connection string, see Connect via Drivers.

    Your connection string should use the following format:

    mongodb://localhost:<port-number>/?directConnection=true
  3. Create the index.

    python create_index.py
    default
1
  1. Install the Atlas CLI.

    If you use Homebrew, you can run the following command in your terminal:

    brew install mongodb-atlas-cli

    For installation instructions on other operating systems, see Install the Atlas CLI

  2. Install Docker.

    Docker requires a network connection for pulling and caching MongoDB images.

  3. Install the MongoDB Database Tools.

    You must install the MongoDB Command Line Database Tools to access the mongorestore command, which you'll use to load the sample data.

2
  1. If you don't have an existing Atlas account, run atlas setup in your terminal or create a new account.

  2. Run atlas deployments setup and follow the prompts to create a local deployment. When prompted to connect to the deployment, select skip.

    For detailed instructions, see Create a Local Atlas Deployment.

3
  1. Run the following command in your terminal to download the sample data:

    curl https://atlas-education.s3.amazonaws.com/sampledata.archive -o sampledata.archive
  2. Run the following command to load the data into your deployment, replacing <port-number> with the port where you're hosting the deployment:

    mongorestore --archive=sampledata.archive --port=<port-number>
4

➤ Use the Select your language drop-down menu to set the client for this tutorial.


  1. When the sample data finishes loading, click Create Search Index.

  2. Make the following selections on the page and then click Next.

    Search Type

    Select the Atlas Search index type.

    Index Name and Data Source

    Specify the following information:

    • Index Name: default

    • Database and Collection:

      • sample_mflix

      • movies

    Configuration Method

    For a guided experience, select Visual Editor.

    To edit the raw index definition, select JSON Editor.
  3. Define the index.

    The following index definition dynamically indexes the fields in the movies collection.

    Review the "default" index definition for the movies collection.

    1. Review the index definition.

      Your index definition should look similar to the following:

      {
      "mappings": {
      "dynamic": true
      }
      }

      The above index definition dynamically indexes the fields of supported types in each document in the movies collection.

    2. Click Next.

  4. Click Create Search Index.

  5. Wait for the index to finish building.

    The index should take about one minute to build. While it is building, the Status column reads Build in Progress. When it is finished building, the Status column reads Active.

  1. Connect to the Atlas cluster using mongosh.

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

  2. Switch to the database that contains the collection for which you want to create the index.

    Example

    use sample_mflix
    switched to db sample_mflix
  3. Run the db.collection.createSearchIndex() method to create the index.

    db.movies.createSearchIndex(
    "default",
    { mappings: { dynamic: true } }
    )
    default
1

Open Compass and connect to your Atlas cluster. For detailed instructions, see Connect via Compass.

2

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

3
  1. Click the Indexes tab, then select Search Indexes.

  2. Click Create Index to open the index creation dialog box.

  3. Specify a name for the index.

    Your Atlas Search index is named default by default. If you keep this name, then your index will be the default Search index for any Atlas Search query that does not specify a different index option in its operators. If you are creating multiple indexes, we recommend that you maintain a consistent, descriptive naming convention across your indexes.

  4. Specify the JSON Atlas Search index definition.

    1{
    2 "analyzer": "<analyzer-for-index>",
    3 "searchAnalyzer": "<analyzer-for-query>",
    4 "mappings": {
    5 "dynamic": <boolean>,
    6 "fields": { <field-definition> }
    7 },
    8 "numPartitions": <integer>,
    9 "analyzers": [ <custom-analyzer> ],
    10 "storedSource": <boolean> | {
    11 <stored-source-definition>
    12 },
    13 "synonyms": [
    14 {
    15 <synonym-mapping-definition>
    16 }
    17 ]
    18}
    19
  5. Click Create Search Index.

  1. Set up and initialize the .NET/C# project.

    # Create a new directory and initialize the project
    mkdir atlas-search-quickstart && cd atlas-search-quickstart
    dotnet new console
    # Add the MongoDB .NET/C# Driver to your project
    dotnet add package MongoDB.Driver

    For more detailed installation instructions, see the MongoDB C# Driver documentation.

  2. Define the index.

    Paste the following code into the Program.cs file.

    Program.cs
    1using MongoDB.Bson;
    2using MongoDB.Driver;
    3
    4// connect to your Atlas deployment
    5var uri = "<connection-string>";
    6
    7var client = new MongoClient(uri);
    8
    9var db = client.GetDatabase("sample_mflix");
    10var collection = db.GetCollection<BsonDocument>("movies");
    11
    12// define your Atlas Search index
    13var index = new CreateSearchIndexModel(
    14 "default", new BsonDocument
    15 {
    16 { "mappings", new BsonDocument
    17 {
    18 { "dynamic", true }
    19 }
    20 }
    21 });
    22
    23var result = collection.SearchIndexes.CreateOne(index);
    24Console.WriteLine(result);

    Your connection string should use the following format:

    mongodb+srv://<db_username>:<db_password>@<clusterName>.<hostname>.mongodb.net

    Note

    Ensure that your connection string includes your database user's credentials. To learn more about finding your connection string, see Connect via Drivers.

    Your connection string should use the following format:

    mongodb://localhost:<port-number>/?directConnection=true
  3. Create the index.

    dotnet run Program.cs
    default
  1. Set up and initialize the Go module.

    # Create a new directory and initialize the project
    mkdir atlas-search-quickstart && cd atlas-search-quickstart
    go mod init atlas-search-quickstart
    # Add the MongoDB Go Driver to your project
    go get go.mongodb.org/mongo-driver/v2/mongo

    For more detailed installation instructions, see the MongoDB Go Driver documentation.

  2. Define the index.

    Paste the following code into a file named create-index.go.

    create-index.go
    1package main
    2
    3import (
    4 "context"
    5 "log"
    6
    7 "go.mongodb.org/mongo-driver/v2/bson"
    8 "go.mongodb.org/mongo-driver/v2/mongo"
    9 "go.mongodb.org/mongo-driver/v2/mongo/options"
    10)
    11
    12func main() {
    13 ctx := context.Background()
    14
    15 // Replace the placeholder with your Atlas connection string
    16 const uri = "<connection-string>"
    17
    18 // Connect to your Atlas cluster
    19 clientOptions := options.Client().ApplyURI(uri)
    20 client, err := mongo.Connect(clientOptions)
    21 if err != nil {
    22 log.Fatalf("failed to connect to the server: %v", err)
    23 }
    24 defer func() { _ = client.Disconnect(ctx) }()
    25
    26 // Set the namespace
    27 coll := client.Database("sample_mflix").Collection("movies")
    28
    29 // Define a simple Atlas Search index
    30 indexName := "default"
    31
    32 // Create the default definition for search index
    33 definition := bson.D{{"mappings", bson.D{{"dynamic", true}}}}
    34 indexModel := mongo.SearchIndexModel{
    35 Definition: definition,
    36 Options: options.SearchIndexes().SetName(indexName),
    37 }
    38
    39 // Create the index
    40 searchIndexName, err := coll.SearchIndexes().CreateOne(ctx, indexModel)
    41 if err != nil {
    42 log.Fatalf("failed to create the search index: %v", err)
    43 }
    44 log.Println("New search index named " + searchIndexName + " is building.")
    45}

    Your connection string should use the following format:

    mongodb+srv://<db_username>:<db_password>@<clusterName>.<hostname>.mongodb.net

    Note

    Ensure that your connection string includes your database user's credentials. To learn more about finding your connection string, see Connect via Drivers.

    Your connection string should use the following format:

    mongodb://localhost:<port-number>/?directConnection=true
  3. Create the index.

    go run create-index.go
  1. Add the Java driver version 4.11 or higher as a dependency in your Java project. Select one of the following tabs, depending on your package manager:

    If you are using Maven, add the following dependencies to the dependencies array in your project's pom.xml file:

    pom.xml
    <dependencies>
    <!-- MongoDB Java Sync Driver v4.11.0 or later -->
    <dependency>
    <groupId>org.mongodb</groupId>
    <artifactId>mongodb-driver-sync</artifactId>
    <version>[4.11.0,)</version>
    </dependency>
    </dependencies>

    If you are using Gradle, add the following to the dependencies array in your project's build.gradle file:

    build.gradle
    dependencies {
    // MongoDB Java Sync Driver v4.11.0 or later
    implementation 'org.mongodb:mongodb-driver-sync:[4.11.0,)'
    }
  2. Run your package manager to install the dependencies to your project.

    For more detailed installation instructions and version compatibility, see the MongoDB Java Driver documentation.

  3. Define the index.

    Paste the following example into a file named CreateIndex.java.

    CreateIndex.java
    1import com.mongodb.client.MongoClient;
    2import com.mongodb.client.MongoClients;
    3import com.mongodb.client.MongoCollection;
    4import com.mongodb.client.MongoDatabase;
    5import org.bson.Document;
    6
    7public class CreateIndex {
    8 public static void main(String[] args) {
    9 // connect to your Atlas cluster
    10 String uri = "<connection-string>";
    11
    12 try (MongoClient mongoClient = MongoClients.create(uri)) {
    13 // set namespace
    14 MongoDatabase database = mongoClient.getDatabase("sample_mflix");
    15 MongoCollection<Document> collection = database.getCollection("movies");
    16
    17 Document index = new Document("mappings",
    18 new Document("dynamic", true));
    19 collection.createSearchIndex(index);
    20 }
    21 }
    22}

    Your connection string should use the following format:

    mongodb+srv://<db_username>:<db_password>@<clusterName>.<hostname>.mongodb.net

    Note

    Ensure that your connection string includes your database user's credentials. To learn more about finding your connection string, see Connect via Drivers.

    Your connection string should use the following format:

    mongodb://localhost:<port-number>/?directConnection=true
  1. Install the MongoDB Kotlin Coroutine Driver.

    Create a new Kotlin project and install the MongoDB Kotlin Coroutine Driver documentation.

  2. Define the index.

    Create a file named CreateIndex.kt. Copy and paste the following code into the file.

    CreateIndex.kt
    1import com.mongodb.MongoException
    2import com.mongodb.client.model.SearchIndexModel
    3import com.mongodb.client.model.SearchIndexType
    4import com.mongodb.kotlin.client.coroutine.MongoClient
    5import kotlinx.coroutines.runBlocking
    6import org.bson.Document
    7
    8fun main() {
    9 // Replace the placeholder with your MongoDB deployment's connection string
    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 val searchIdx = Document(
    15 "mappings",
    16 Document("dynamic", true)
    17 )
    18 runBlocking {
    19 try {
    20 val result = collection.createSearchIndex("default", searchIdx)
    21 println("Index created: $result")
    22 } catch (e: MongoException) {
    23 println("Failed to create search index: ${e.message}")
    24 } finally {
    25 mongoClient.close()
    26 }
    27 }
    28}

    Your connection string should use the following format:

    mongodb+srv://<db_username>:<db_password>@<clusterName>.<hostname>.mongodb.net

    Note

    Ensure that your connection string includes your database user's credentials. To learn more about finding your connection string, see Connect via Drivers.

    Your connection string should use the following format:

    mongodb://localhost:<port-number>/?directConnection=true
  3. Run the CreateIndex.kt file in your IDE.

  1. Initialize your Node.js project.

    # Create a new directory and initialize the project
    mkdir atlas-search-quickstart && cd atlas-search-quickstart
    npm init -y
    # Add the MongoDB Node.js Driver to your project
    npm install mongodb

    For detailed installation instructions, see the MongoDB Node Driver documentation.

  2. Define the index.

    Paste the following code into a file named create-index.js.

    create-index.js
    1const { MongoClient } = require("mongodb");
    2
    3// connect to your Atlas deployment
    4const uri =
    5 "<connection-string>";
    6
    7const client = new MongoClient(uri);
    8
    9async function run() {
    10 try {
    11
    12 // set namespace
    13 const database = client.db("sample_mflix");
    14 const collection = database.collection("movies");
    15
    16 // define your Atlas Search index
    17 const index = {
    18 name: "default",
    19 definition: {
    20 /* search index definition fields */
    21 "mappings": {
    22 "dynamic": true
    23 }
    24 }
    25 }
    26
    27 // run the helper method
    28 const result = await collection.createSearchIndex(index);
    29 console.log(result);
    30 } finally {
    31 await client.close();
    32 }
    33}
    34
    35run().catch(console.dir);

    Your connection string should use the following format:

    mongodb+srv://<db_username>:<db_password>@<clusterName>.<hostname>.mongodb.net

    Note

    Ensure that your connection string includes your database user's credentials. To learn more about finding your connection string, see Connect via Drivers.

    Your connection string should use the following format:

    mongodb://localhost:<port-number>/?directConnection=true
  3. Create the index.

    node create-index.js
    default
  1. Install the MongoDB Python Driver.

    pip install pymongo

    For detailed installation instructions, see MongoDB Python Driver (PyMongo).

  2. Define the index.

    Paste the following code into a file named create_index.py.

    create_index.py
    1from pymongo import MongoClient
    2from pymongo.operations import SearchIndexModel
    3
    4# connect to your Atlas deployment
    5uri = "<connection-string>"
    6client = MongoClient(uri)
    7
    8# set namespace
    9database = client["sample_mflix"]
    10collection = database["movies"]
    11
    12# define your Atlas Search index
    13search_index_model = SearchIndexModel(
    14 definition={
    15 "mappings": {
    16 "dynamic": True
    17 },
    18 },
    19 name="default",
    20)
    21
    22# create the index
    23result = collection.create_search_index(model=search_index_model)
    24print(result)

    Your connection string should use the following format:

    mongodb+srv://<db_username>:<db_password>@<clusterName>.<hostname>.mongodb.net

    Note

    Ensure that your connection string includes your database user's credentials. To learn more about finding your connection string, see Connect via Drivers.

    Your connection string should use the following format:

    mongodb://localhost:<port-number>/?directConnection=true
  3. Create the index.

    python create_index.py
    default

In this section, you run queries against the indexed collection.

1

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.

    If you have no clusters, click Create cluster to create one. To learn more, see Create a Cluster.

  2. If your project has multiple clusters, select the cluster you want to use from the Select cluster dropdown, then 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.

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

Run a basic $search query by using the text operator.

This query has the following search criteria:

  • The plot field must contain the word baseball.

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

1[
2 {
3 $search:
4 {
5 text: {
6 query: "baseball",
7 path: "plot"
8 }
9 }
10 }
11]
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
...
...

Note

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.

5

Atlas Search provides several operators that you can use to build complex queries and retrieve more specific results for your use case. Update your $search query to use the compound operator to combine multiple operators into a single query.

This query has the following search criteria:

  • The plot field must contain the word baseball.

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

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

1[
2 {
3 "$search": {
4 "compound": {
5 "must": [
6 {
7 "text": {
8 "query": "baseball",
9 "path": "plot"
10 }
11 }
12 ],
13 "mustNot": [
14 {
15 "text": {
16 "query": ["Comedy", "Romance"],
17 "path": "genres"
18 }
19 }
20 ]
21 }
22 }
23 }
24]
SCORE: 3.4706974029541016 _id: "573a1393f29313caabcdca79"
title: "The Pride of the Yankees"
plot: "The story of the life and career of the famed baseball player, Lou Geh…"
genres: ["Biography", "Drama", "Family"]
...
SCORE: 3.4706974029541016 _id: "573a1399f29313caabcecef1"
title: "The Babe"
plot: "Babe Ruth becomes a baseball legend but is unheroic to those who know …"
genres: ["Biography", "Drama", "Sport"]
...
SCORE: 3.406810760498047 _id: "573a13bdf29313caabd5813d"
title: "Sugar"
plot: "Dominican baseball star Miguel \"Sugar\" Santos is recruited to play in …"
genres: ["Drama", "Sport"]
...
...
6

Atlas Search provides several search options that you can use to further process your Atlas Search query results. Add the sort option to your query to display the results in a specific order.

This query has the following search criteria:

  • The plot field must contain the word baseball.

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

  • Sort the results by the released date field in descending order. Atlas Search returns the most recent movies first.

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

1[
2 {
3 "$search": {
4 "compound": {
5 "must": [
6 {
7 "text": {
8 "query": "baseball",
9 "path": "plot"
10 }
11 }
12 ],
13 "mustNot": [
14 {
15 "text": {
16 "query": ["Comedy", "Romance"],
17 "path": "genres"
18 }
19 }
20 ]
21 },
22 "sort": {
23 "released": -1
24 }
25 }
26 }
27]
SCORE: 3.173170804977417 _id: "573a13ccf29313caabd832f5"
plot: "A sports agent stages an unconventional recruitment strategy to get ta…"
title: "Million Dollar Arm"
genres: Array (3)
released: 2014-05-16T00:00:00.000+00:00
...
SCORE: 3.2858426570892334 _id: "573a13d9f29313caabda97d8"
plot: "A Taiwanese high school baseball team travels to Japan in 1931 to comp…"
title: "Kano"
genres: Array (3)
released: 2014-02-27T00:00:00.000+00:00
...
SCORE: 2.4570295810699463 _id: "573a13daf29313caabdad92d"
plot: "12-year-old Josh is a mixed race boy and a promising baseball player..."
title: "Calloused Hands"
genres: Array (1)
released: 2013-03-03T00:00:00.000+00:00
...
...
1

Run a basic $search query by using the text operator.

This query has the following search criteria:

  • The plot field must contain the word baseball.

  • $limit and $project stages to return only 3 documents and the title and plot fields.

1db.movies.aggregate([
2 {
3 $search:
4 {
5 "text": {
6 "query": "baseball",
7 "path": "plot"
8 }
9 }
10 },
11 {
12 $limit: 3
13 },
14 {
15 $project: {
16 "_id": 0,
17 "title": 1,
18 "plot": 1
19 }
20 }
21])
{
"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"
}
2

Atlas Search provides several operators that you can use to build complex queries and retrieve more specific results for your use case. Update your $search query to use the compound operator to combine multiple operators into a single query.

This query has the following search criteria:

  • The plot field must contain the word baseball.

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

  • $limit and $project stages to return only 3 documents and the title, plot, and genres fields.

1db.movies.aggregate([
2 {
3 $search: {
4 "compound": {
5 "must": [
6 {
7 "text": {
8 "query": "baseball",
9 "path": "plot"
10 }
11 }
12 ],
13 "mustNot": [
14 {
15 "text": {
16 "query": ["Comedy", "Romance"],
17 "path": "genres"
18 }
19 }
20 ]
21 }
22 }
23 },
24 {
25 $limit: 3
26 },
27 {
28 $project: {
29 "_id": 0,
30 "title": 1,
31 "plot": 1,
32 "genres": 1
33 }
34 }
35])
[
{
plot: 'The story of the life and career of the famed baseball player, Lou Gehrig.',
genres: [ 'Biography', 'Drama', 'Family' ],
title: 'The Pride of the Yankees'
},
{
plot: 'Babe Ruth becomes a baseball legend but is unheroic to those who know him.',
genres: [ 'Biography', 'Drama', 'Sport' ],
title: 'The Babe'
},
{
plot: 'Dominican baseball star Miguel "Sugar" Santos is recruited to play in the U.S. minor-leagues.',
genres: [ 'Drama', 'Sport' ],
title: 'Sugar'
}
]
3

Atlas Search provides several search options that you can use to further process your Atlas Search query results. Add the sort option to your query to display the results in a specific order.

This query has the following search criteria:

  • The plot field must contain the word baseball.

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

  • Sort the results by the released date field in descending order. Atlas Search returns the most recent movies first.

  • $limit and $project stages to return only 3 documents and the title, plot, genres, and released fields.

1db.movies.aggregate([
2 {
3 $search: {
4 "compound": {
5 "must": [ {
6 "text": {
7 "query": "baseball",
8 "path": "plot"
9 }
10 }],
11 "mustNot": [ {
12 "text": {
13 "query": ["Comedy", "Romance"],
14 "path": "genres"
15 }
16 } ]
17 },
18 "sort": {
19 "released": -1
20 }
21 }
22 },
23 {
24 $limit: 3
25 },
26 {
27 $project: {
28 "_id": 0,
29 "title": 1,
30 "plot": 1,
31 "genres": 1,
32 "released": 1
33 }
34 }
35])
[
{
plot: 'A sports agent stages an unconventional recruitment strategy to get talented Indian cricket players to play Major League Baseball.',
genres: [ 'Biography', 'Drama', 'Sport' ],
title: 'Million Dollar Arm',
released: ISODate('2014-05-16T00:00:00.000Z')
},
{
plot: 'A Taiwanese high school baseball team travels to Japan in 1931 to compete in a national tournament.',
genres: [ 'Biography', 'Drama', 'History' ],
title: 'Kano',
released: ISODate('2014-02-27T00:00:00.000Z')
},
{
plot: "12-year-old Josh is a mixed race boy and a promising baseball player...",
genres: [ 'Drama' ],
title: 'Calloused Hands',
released: ISODate('2013-03-03T00:00:00.000Z')
}
]
1

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

2

Run a basic $search query by using the text operator.

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.

    This query has the following search criteria:

    • The plot field must contain the word baseball.

    • $limit and $project stages to return only 3 documents and the title and plot fields.

    Pipeline Stage
    Query

    $search

    {
    "text": {
    "query": "baseball",
    "path": "plot"
    }
    }

    $limit

    3

    $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"
}
3

Atlas Search provides several operators that you can use to build complex queries and retrieve more specific results for your use case. Update your $search query to use the compound operator to combine multiple operators into a single query.

This query has the following search criteria:

  • The plot field must contain the word baseball.

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

  • $limit and $project stages to return only 3 documents and the title, plot, and genres fields.

Update the following pipeline stages in MongoDB Compass:

Pipeline Stage
Query

$search

{
"compound": {
"must": [
{
"text": {
"query": "baseball",
"path": "plot"
}
}
],
"mustNot": [
{
"text": {
"query": ["Comedy", "Romance"],
"path": "genres"
}
}
]
}
}

$project

{
"_id": 0,
"title": 1,
"plot": 1,
"genres": 1,
}

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

{
"plot" : "The story of the life and career of the famed baseball player, Lou Gehrig.",
"genres" : [ "Biography", "Drama", "Family" ],
"title" : "The Pride of the Yankees"
}
{
"plot" : "Babe Ruth becomes a baseball legend but is unheroic to those who know him.",
"genres" : [ "Biography", "Drama", "Sport" ],
"title" : "The Babe"
}
{
"plot" : "Dominican baseball star Miguel \"Sugar\" Santos is recruited to play in the U.S. minor-leagues.",
"genres" : [ "Drama", "Sport" ],
"title" : "Sugar"
}
4

Atlas Search provides several search options that you can use to further process your Atlas Search query results. Add the sort option to your query to display the results in a specific order.

This query has the following search criteria:

  • The plot field must contain the word baseball.

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

  • Sort the results by the released date field in descending order. Atlas Search returns the most recent movies first.

  • $limit and $project stages to return only 3 documents and the title, plot, genres, and released fields.

Update the following pipeline stages in MongoDB Compass:

Pipeline Stage
Query

$search

{
"compound": {
"must": [
{
"text": {
"query": "baseball",
"path": "plot"
}
}
],
"mustNot": [
{
"text": {
"query": ["Comedy", "Romance"],
"path": "genres"
}
}
]
},
"sort": {
"released": -1
}
}

$project

{
"_id": 0,
"title": 1,
"plot": 1,
"genres": 1,
"released": 1,
}

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

[
{
plot: 'A sports agent stages an unconventional recruitment strategy to get talented Indian cricket players to play Major League Baseball.',
genres: [ 'Biography', 'Drama', 'Sport' ],
title: 'Million Dollar Arm',
released: 2014-05-16T00:00:00.000+00:00
},
{
plot: 'A Taiwanese high school baseball team travels to Japan in 1931 to compete in a national tournament.',
genres: [ 'Biography', 'Drama', 'History' ],
title: 'Kano',
released: 2014-02-27T00:00:00.000+00:00
},
{
plot: "12-year-old Josh is a mixed race boy and a promising baseball player...",
genres: [ 'Drama' ],
title: 'Calloused Hands',
released: 2013-03-03T00:00:00.000+00:00
}
]
1

Run a basic $search query by using the text operator.

  1. Replace the contents of the Program.cs file with the following code.

    This query has the following search criteria:

    • The plot field must contain the word baseball.

    • $limit and $project stages to return only 3 documents and the title and plot fields.

    1using MongoDB.Bson;
    2using MongoDB.Bson.Serialization.Attributes;
    3using MongoDB.Bson.Serialization.Conventions;
    4using MongoDB.Driver;
    5using MongoDB.Driver.Search;
    6
    7public class BasicQuery
    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(3)
    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}
  2. Specify the <connection-string>, then run the query:

    dotnet run Program.cs
    { "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" }
2

Atlas Search provides several operators that you can use to build complex queries and retrieve more specific results for your use case. Update your $search query to use the compound operator to combine multiple operators into a single query.

  1. Modify your Program.cs file with the following code.

    This query has the following search criteria:

    • The plot field must contain the word baseball.

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

    • $limit and $project stages to return only 3 documents and the title, plot, and genres fields.

    1using MongoDB.Bson;
    2using MongoDB.Bson.Serialization.Attributes;
    3using MongoDB.Bson.Serialization.Conventions;
    4using MongoDB.Driver;
    5using MongoDB.Driver.Search;
    6
    7public class CompoundQuery
    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[] genres = { "Comedy", "Romance" };
    24
    25 // define and run pipeline
    26 var results = moviesCollection.Aggregate()
    27 .Search(Builders<MovieDocument>.Search.Compound()
    28 .Must(Builders<MovieDocument>.Search.Text(movie => movie.Plot, "baseball"))
    29 .MustNot((Builders<MovieDocument>.Search.Text(movie => movie.Genres, genres))))
    30 .Project<MovieDocument>(Builders<MovieDocument>.Projection
    31 .Exclude(movie => movie.Id)
    32 .Include(movie => movie.Plot)
    33 .Include(movie => movie.Title)
    34 .Include(movie => movie.Genres))
    35 .Limit(3)
    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 Plot { get; set; }
    52 public string Title { get; set; }
    53 public string[] Genres { get; set; }
    54}
  2. Specify the <connection-string>, then run the query:

    dotnet run Program.cs
    { "plot" : "The story of the life and career of the famed baseball player, Lou Gehrig.", "title" : "The Pride of the Yankees", "genres" : ["Biography", "Drama", "Family"] }
    { "plot" : "Babe Ruth becomes a baseball legend but is unheroic to those who know him.", "title" : "The Babe", "genres" : ["Biography", "Drama", "Sport"] }
    { "plot" : "Dominican baseball star Miguel \"Sugar\" Santos is recruited to play in the U.S. minor-leagues.", "title" : "Sugar", "genres" : ["Drama", "Sport"] }
3

Atlas Search provides several search options that you can use to further process your Atlas Search query results. Add the sort option to your query to display the results in a specific order.

  1. Modify your Program.cs file with the following code.

    This query has the following search criteria:

    • The plot field must contain the word baseball.

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

    • Sort the results by the released date field in descending order. Atlas Search returns the most recent movies first.

    • $limit and $project stages to return only 3 documents and the title, plot, genres, and released fields.

    1using MongoDB.Bson;
    2using MongoDB.Bson.Serialization.Attributes;
    3using MongoDB.Bson.Serialization.Conventions;
    4using MongoDB.Driver;
    5using MongoDB.Driver.Search;
    6
    7public class SortQuery
    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[] genres = { "Comedy", "Romance" };
    24
    25 // define search options
    26 var searchOptions = new SearchOptions<MovieDocument>()
    27 {
    28 Sort = Builders<MovieDocument>.Sort.Descending(movie => movie.Released),
    29 };
    30
    31 // define and run pipeline
    32 var results = moviesCollection.Aggregate()
    33 .Search(Builders<MovieDocument>.Search.Compound()
    34 .Must(Builders<MovieDocument>.Search.Text(movie => movie.Plot, "baseball"))
    35 .MustNot((Builders<MovieDocument>.Search.Text(movie => movie.Genres, genres))), searchOptions)
    36 .Project<MovieDocument>(Builders<MovieDocument>.Projection
    37 .Exclude(movie => movie.Id)
    38 .Include(movie => movie.Plot)
    39 .Include(movie => movie.Title)
    40 .Include(movie => movie.Genres)
    41 .Include(movie => movie.Released))
    42 .Limit(3)
    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 DateTime Released { get; set; }
    62}
  2. Specify the <connection-string>, then run the query:

    dotnet run Program.cs
    { "plot" : "A sports agent stages an unconventional recruitment strategy to get talented Indian cricket players to play Major League Baseball.", "title" : "Million Dollar Arm", "genres" : ["Biography", "Drama", "Sport"], "released" : { "$date" : "2014-05-16T00:00:00Z" } }
    { "plot" : "A Taiwanese high school baseball team travels to Japan in 1931 to compete in a national tournament.", "title" : "Kano", "genres" : ["Biography", "Drama", "History"], "released" : { "$date" : "2014-02-27T00:00:00Z" } }
    { "plot" : "12-year-old Josh is a mixed race boy and a promising baseball player. He is abused by his mother's boyfriend Byrd, and neglected by his mother Debbie. He forges his own path in life when ...", "title" : "Calloused Hands", "genres" : ["Drama"], "released" : { "$date" : "2013-03-03T00:00:00Z" } }
1

Run a basic $search query by using the text operator.

  1. Create a new file named run-query.go and paste the following code.

    This query has the following search criteria:

    • The plot field must contain the word baseball.

    • $limit and $project stages to return only 3 documents and the title and plot fields.

    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 var err error
    15 // connect to the Atlas cluster
    16 ctx := context.Background()
    17 client, err := mongo.Connect(options.Client().SetTimeout(5 * time.Second).ApplyURI("<connection-string>"))
    18 if err != nil {
    19 panic(err)
    20 }
    21 defer client.Disconnect(ctx)
    22 // set namespace
    23 collection := client.Database("sample_mflix").Collection("movies")
    24 // define pipeline
    25 searchStage := bson.D{{"$search", bson.D{
    26 {"text", bson.D{
    27 {"path", "plot"},
    28 {"query", "baseball"},
    29 }},
    30 }}}
    31 limitStage := bson.D{{"$limit", 3}}
    32 projectStage := bson.D{{"$project", bson.D{{"title", 1}, {"plot", 1}, {"_id", 0}}}}
    33 // run pipeline
    34 cursor, err := collection.Aggregate(ctx, mongo.Pipeline{searchStage, limitStage, projectStage})
    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}
  2. Specify the <connection-string>, then run the query:

    go run run-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"}
2

Atlas Search provides several operators that you can use to build complex queries and retrieve more specific results for your use case. Update your $search query to use the compound operator to combine multiple operators into a single query.

  1. Modify run-query.go to use the compound query.

    This query has the following search criteria:

    • The plot field must contain the word baseball.

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

    • $limit and $project stages to return only 3 documents and the title, plot, and genres fields.

    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 var err error
    15 // connect to the Atlas cluster
    16 ctx := context.Background()
    17 client, err := mongo.Connect(options.Client().SetTimeout(5 * time.Second).ApplyURI("<connection-string>"))
    18 if err != nil {
    19 panic(err)
    20 }
    21 defer client.Disconnect(ctx)
    22 // set namespace
    23 collection := client.Database("sample_mflix").Collection("movies")
    24 // define pipeline
    25 searchStage := bson.D{{"$search", bson.M{
    26 "compound": bson.M{
    27 "must": bson.A{
    28 bson.M{
    29 "text": bson.D{
    30 {"path", "plot"}, {"query", "baseball"},
    31 },
    32 },
    33 },
    34 "mustNot": bson.A{
    35 bson.M{
    36 "text": bson.M{
    37 "path": "genres", "query": []string{"Comedy", "Romance"},
    38 },
    39 },
    40 },
    41 },
    42 }}}
    43 limitStage := bson.D{{"$limit", 3}}
    44 projectStage := bson.D{{"$project", bson.D{{"title", 1}, {"plot", 1}, {"genres", 1}, {"_id", 0}}}}
    45 // run pipeline
    46 cursor, err := collection.Aggregate(ctx, mongo.Pipeline{searchStage, limitStage, projectStage})
    47 if err != nil {
    48 panic(err)
    49 }
    50 // print results
    51 var results []bson.D
    52 if err = cursor.All(context.TODO(), &results); err != nil {
    53 panic(err)
    54 }
    55 for _, result := range results {
    56 fmt.Println(result)
    57 }
    58}
  2. Specify the <connection-string>, then run the query:

    go run run-query.go
    {"plot":"The story of the life and career of the famed baseball player, Lou Gehrig.","genres":["Biography","Drama","Family"],"title":"The Pride of the Yankees"}
    {"plot":"Babe Ruth becomes a baseball legend but is unheroic to those who know him.","genres":["Biography","Drama","Sport"],"title":"The Babe"}
    {"plot":"Dominican baseball star Miguel \"Sugar\" Santos is recruited to play in the U.S. minor-leagues.","genres":["Drama","Sport"],"title":"Sugar"}
3

Atlas Search provides several search options that you can use to further process your Atlas Search query results. Add the sort option to your query to display the results in a specific order.

  1. Modify run-query.go to add the sort option.

    This query has the following search criteria:

    • The plot field must contain the word baseball.

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

    • Sort the results by the released date field in descending order. Atlas Search returns the most recent movies first.

    • $limit and $project stages to return only 3 documents and the title, plot, genres, and released fields.

    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 var err error
    15 // connect to the Atlas cluster
    16 ctx := context.Background()
    17 client, err := mongo.Connect(options.Client().SetTimeout(5 * time.Second).ApplyURI("<connection-string>"))
    18 if err != nil {
    19 panic(err)
    20 }
    21 defer client.Disconnect(ctx)
    22 // set namespace
    23 collection := client.Database("sample_mflix").Collection("movies")
    24 // define pipeline
    25 searchStage := bson.D{{"$search", bson.M{
    26 "compound": bson.M{
    27 "must": bson.A{
    28 bson.M{
    29 "text": bson.D{
    30 {"path", "plot"}, {"query", "baseball"},
    31 },
    32 },
    33 },
    34 "mustNot": bson.A{
    35 bson.M{
    36 "text": bson.M{
    37 "path": "genres", "query": []string{"Comedy", "Romance"},
    38 },
    39 },
    40 },
    41 },
    42 "sort": bson.D{
    43 {"released", -1},
    44 },
    45 }}}
    46 limitStage := bson.D{{"$limit", 3}}
    47 projectStage := bson.D{{"$project", bson.D{{"_id", 0}, {"title", 1}, {"plot", 1}, {"genres", 1}, {"released", 1}}}}
    48 // run pipeline
    49 cursor, err := collection.Aggregate(ctx, mongo.Pipeline{searchStage, limitStage, projectStage})
    50 if err != nil {
    51 panic(err)
    52 }
    53 // print results
    54 var results []bson.D
    55 if err = cursor.All(context.TODO(), &results); err != nil {
    56 panic(err)
    57 }
    58 for _, result := range results {
    59 fmt.Println(result)
    60 }
    61}
  2. Specify the <connection-string>, then run the query:

    go run run-query.go
    {"plot":"A sports agent stages an unconventional recruitment strategy to get talented Indian cricket players to play Major League Baseball.","genres":["Biography","Drama","Sport"],"title":"Million Dollar Arm","released":{"$date":{"$numberLong":"1400198400000"}}}
    {"plot":"A Taiwanese high school baseball team travels to Japan in 1931 to compete in a national tournament.","genres":["Biography","Drama","History"],"title":"Kano","released":{"$date":{"$numberLong":"1393459200000"}}}
    {"plot":"12-year-old Josh is a mixed race boy and a promising baseball player. He is abused by his mother's boyfriend Byrd, and neglected by his mother Debbie. He forges his own path in life when ...","genres":["Drama"],"title":"Calloused Hands","released":{"$date":{"$numberLong":"1362268800000"}}}
1

Ensure that your CLASSPATH contains the following libraries.

junit

4.11.0 or higher version

mongodb-driver-sync

4.11.0 or higher version

slf4j-log4j12

1.7.30 or higher version

For more detailed installation instructions and version compatibility, see the MongoDB Java Driver documentation.

2

Run a basic $search query by using the text operator.

  1. Create a new file named RunQuery.java and paste the following code.

    This query has the following search criteria:

    • The plot field must contain the word baseball.

    • $limit and $project stages to return only 3 documents and the title and plot fields.

    1import java.util.Arrays;
    2import java.util.List;
    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 RunQuery {
    15 public static void main( String[] args ) {
    16 String uri = "<connection-string>";
    17
    18 try (MongoClient mongoClient = MongoClients.create(uri)) {
    19 MongoDatabase database = mongoClient.getDatabase("sample_mflix");
    20 MongoCollection<Document> collection = database.getCollection("movies");
    21
    22 Document textQuery = new Document("query", "baseball").append("path","plot");
    23
    24 Document searchStage = new Document("$search",
    25 new Document("index", "default")
    26 .append("text", textQuery));
    27
    28 collection.aggregate(Arrays.asList(
    29 searchStage,
    30 limit(3),
    31 project(fields(excludeId(), include("title", "plot"))))
    32 ).forEach(doc -> System.out.println(doc.toJson()));
    33 }
    34 }
    35}

    Note

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

    package com.mongodb.drivers;
  2. Specify the <connection-string>, then run the query:

    javac RunQuery.java
    java RunQuery
    {"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"}
3

Atlas Search provides several operators that you can use to build complex queries and retrieve more specific results for your use case. Update your $search query to use the compound operator to combine multiple operators into a single query.

  1. Modify RunQuery.java to use the compound query.

    This query has the following search criteria:

    • The plot field must contain the word baseball.

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

    • $limit and $project stages to return only 3 documents and the title, plot, and genres fields.

    1import java.util.Arrays;
    2import java.util.List;
    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 RunQuery {
    15 public static void main( String[] args ) {
    16 String uri = "<connection-string>";
    17
    18 try (MongoClient mongoClient = MongoClients.create(uri)) {
    19 MongoDatabase database = mongoClient.getDatabase("sample_mflix");
    20 MongoCollection<Document> collection = database.getCollection("movies");
    21
    22 Document compound = new Document("must", Arrays.asList(
    23 new Document("text", new Document("query", "baseball").append("path", "plot"))))
    24 .append("mustNot", Arrays.asList(
    25 new Document("text", new Document("query", Arrays.asList("Comedy", "Romance")).append("path", "genres"))));
    26
    27 Document searchStage = new Document("$search",
    28 new Document("index", "default")
    29 .append("compound", compound));
    30
    31 collection.aggregate(Arrays.asList(
    32 searchStage,
    33 limit(3),
    34 project(fields(excludeId(), include("title", "plot", "genres"))))
    35 ).forEach(doc -> System.out.println(doc.toJson()));
    36 }
    37 }
    38}
  2. Specify the <connection-string>, then run the query:

    javac RunQuery.java
    java RunQuery
    {"plot": "The story of the life and career of the famed baseball player, Lou Gehrig.", "genres": ["Biography", "Drama", "Family"], "title": "The Pride of the Yankees"}
    {"plot": "Babe Ruth becomes a baseball legend but is unheroic to those who know him.", "genres": ["Biography", "Drama", "Sport"], "title": "The Babe"}
    {"plot": "Dominican baseball star Miguel \"Sugar\" Santos is recruited to play in the U.S. minor-leagues.", "genres": ["Drama", "Sport"], "title": "Sugar"}
4

Atlas Search provides several search options that you can use to further process your Atlas Search query results. Add the sort option to your query to display the results in a specific order.

  1. Modify RunQuery.java to add the sort option.

    This query has the following search criteria:

    • The plot field must contain the word baseball.

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

    • Sort the results by the released date field in descending order. Atlas Search returns the most recent movies first.

    • $limit and $project stages to return only 3 documents and the title, plot, genres, and released fields.

    1import java.util.Arrays;
    2import java.util.List;
    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 RunQuery {
    15 public static void main( String[] args ) {
    16 String uri = "<connection-string>";
    17
    18 try (MongoClient mongoClient = MongoClients.create(uri)) {
    19 MongoDatabase database = mongoClient.getDatabase("sample_mflix");
    20 MongoCollection<Document> collection = database.getCollection("movies");
    21
    22 Document compound = new Document("must", Arrays.asList(
    23 new Document("text", new Document("query", "baseball").append("path", "plot"))))
    24 .append("mustNot", Arrays.asList(
    25 new Document("text", new Document("query", Arrays.asList("Comedy", "Romance")).append("path", "genres"))));
    26
    27 Document searchStage = new Document("$search",
    28 new Document("index", "default")
    29 .append("compound", compound)
    30 .append("sort", new Document("released", -1)));
    31
    32 collection.aggregate(Arrays.asList(
    33 searchStage,
    34 limit(3),
    35 project(fields(excludeId(), include("title", "plot", "genres", "released"))))
    36 ).forEach(doc -> System.out.println(doc.toJson()));
    37 }
    38 }
    39}
  2. Specify the <connection-string>, then run the query:

    javac RunQuery.java
    java RunQuery
    {"plot": "A sports agent stages an unconventional recruitment strategy to get talented Indian cricket players to play Major League Baseball.", "genres": ["Biography", "Drama", "Sport"], "title": "Million Dollar Arm", "released": {"$date": "2014-05-16T00:00:00Z"}}
    {"plot": "A Taiwanese high school baseball team travels to Japan in 1931 to compete in a national tournament.", "genres": ["Biography", "Drama", "History"], "title": "Kano", "released": {"$date": "2014-02-27T00:00:00Z"}}
    {"plot": "12-year-old Josh is a mixed race boy and a promising baseball player. He is abused by his mother's boyfriend Byrd, and neglected by his mother Debbie. He forges his own path in life when ...", "genres": ["Drama"], "title": "Calloused Hands", "released": {"$date": "2013-03-03T00:00:00Z"}}
1

Run a basic $search query by using the text operator.

  1. Create a new file named RunQuery.kt and paste the following code.

    This query has the following search criteria:

    • The plot field must contain the word baseball.

    • $limit and $project stages to return only 3 documents and the title and plot fields.

    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(3),
    25 project(fields(excludeId(), include("title", "plot")))
    26 )
    27 )
    28 resultsFlow.collect { println(it) }
    29 }
    30 mongoClient.close()
    31}
  2. Specify the <connection-string>, then run the query:

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

    Document{{plot=The story of the life and career of the famed baseball player, Lou Gehrig., genres=[Biography, Drama, Family], title=The Pride of the Yankees}}
    Document{{plot=Babe Ruth becomes a baseball legend but is unheroic to those who know him., genres=[Biography, Drama, Sport], title=The Babe}}
    Document{{plot=Dominican baseball star Miguel "Sugar" Santos is recruited to play in the U.S. minor-leagues., genres=[Drama, Sport], title=Sugar}}
2

Atlas Search provides several operators that you can use to build complex queries and retrieve more specific results for your use case. Update your $search query to use the compound operator to combine multiple operators into a single query.

  1. Modify RunQuery.kt to use the compound query.

    This query has the following search criteria:

    • The plot field must contain the word baseball.

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

    • $limit and $project stages to return only 3 documents and the title, plot, and genres fields.

    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 compoundQuery = Document(
    19 "must", listOf(
    20 Document("text", Document("query", "baseball")
    21 .append("path", "plot"))
    22 )
    23 )
    24 .append(
    25 "mustNot", listOf(
    26 Document("text", Document("query", listOf("Comedy", "Romance"))
    27 .append("path", "genres"))
    28 )
    29 )
    30
    31 // run query and print results
    32 val resultsFlow = collection.aggregate<Document>(
    33 listOf(
    34 eq("\$search", eq("compound", compoundQuery)),
    35 limit(3),
    36 project(fields(
    37 excludeId(),
    38 include("title", "plot", "genres")
    39 ))
    40 )
    41 )
    42 resultsFlow.collect { println(it) }
    43 }
    44 mongoClient.close()
    45}
  2. Specify the <connection-string>, then run the query.

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

    Document{{plot=The story of the life and career of the famed baseball player, Lou Gehrig., genres=[Biography, Drama, Family], title=The Pride of the Yankees}}
    Document{{plot=Babe Ruth becomes a baseball legend but is unheroic to those who know him., genres=[Biography, Drama, Sport], title=The Babe}}
    Document{{plot=Dominican baseball star Miguel "Sugar" Santos is recruited to play in the U.S. minor-leagues., genres=[Drama, Sport], title=Sugar}}
3

Atlas Search provides several search options that you can use to further process your Atlas Search query results. Add the sort option to your query to display the results in a specific order.

  1. Modify RunQuery.kt to add the sort option.

    This query has the following search criteria:

    • The plot field must contain the word baseball.

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

    • Sort the results by the released date field in descending order. Atlas Search returns the most recent movies first.

    • $limit and $project stages to return only 3 documents and the title, plot, genres, and released fields.

    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 compoundQuery = Document(
    19 "must", listOf(
    20 Document("text", Document("query", "baseball")
    21 .append("path", "plot"))
    22 )
    23 )
    24 .append(
    25 "mustNot", listOf(
    26 Document("text", Document("query", listOf("Comedy", "Romance"))
    27 .append("path", "genres"))
    28 )
    29 )
    30
    31 // sort configuration
    32 val sortConfig = Document("released", -1)
    33
    34 // run query and print results
    35 val resultsFlow = collection.aggregate<Document>(
    36 listOf(
    37 Document("\$search", Document("compound", compoundQuery).append("sort", sortConfig)),
    38 limit(3),
    39 project(fields(
    40 excludeId(),
    41 include("title", "plot", "genres", "released")
    42 ))
    43 )
    44 )
    45 resultsFlow.collect { println(it) }
    46 }
    47 mongoClient.close()
    48}
  2. Specify the <connection-string>, then run the query:

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

    Document{{plot=A sports agent stages an unconventional recruitment strategy to get talented Indian cricket players to play Major League Baseball., genres=[Biography, Drama, Sport], title=Million Dollar Arm, released=Thu May 15 19:00:00 CDT 2014}}
    Document{{plot=A Taiwanese high school baseball team travels to Japan in 1931 to compete in a national tournament., genres=[Biography, Drama, History], title=Kano, released=Wed Feb 26 18:00:00 CST 2014}}
    Document{{plot=12-year-old Josh is a mixed race boy and a promising baseball player. He is abused by his mother's boyfriend Byrd, and neglected by his mother Debbie. He forges his own path in life when ..., genres=[Drama], title=Calloused Hands, released=Sat Mar 02 18:00:00 CST 2013}}
1

Run a basic $search query by using the text operator.

  1. Create a new file named run-query.js and paste the following code.

    This query has the following search criteria:

    • The plot field must contain the word baseball.

    • $limit and $project stages to return only 3 documents and the title and plot fields.

    1const { MongoClient } = require("mongodb");
    2
    3async function main() {
    4 // Replace the placeholder with your connection string
    5 const uri = "<connection-string>";
    6 const client = new MongoClient(uri);
    7
    8 try {
    9 await client.connect();
    10 const database = client.db("sample_mflix");
    11 const movies = database.collection("movies");
    12
    13 const query = [
    14 {
    15 $search:
    16 {
    17 text: {
    18 query: "baseball",
    19 path: "plot",
    20 },
    21 }
    22 },
    23 {
    24 $limit: 3,
    25 },
    26 {
    27 $project: {
    28 _id: 0,
    29 title: 1,
    30 plot: 1,
    31 },
    32 },
    33 ];
    34
    35 const cursor = movies.aggregate(query);
    36 await cursor.forEach(doc => console.log(doc));
    37 } finally {
    38 await client.close();
    39 }
    40}
    41
    42main().catch(console.error);
  2. Specify the <connection-string>, then run the query:

    node run-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'
    }
2

Atlas Search provides several operators that you can use to build complex queries and retrieve more specific results for your use case. Update your $search query to use the compound operator to combine multiple operators into a single query.

  1. Modify run-query.js to use the compound query.

    This query has the following search criteria:

    • The plot field must contain the word baseball.

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

    • $limit and $project stages to return only 3 documents and the title, plot, and genres fields.

    1const { MongoClient } = require("mongodb");
    2
    3async function main() {
    4 // Replace the placeholder with your connection string
    5 const uri = "<connection-string>";
    6 const client = new MongoClient(uri);
    7
    8 try {
    9 await client.connect();
    10 const database = client.db("sample_mflix");
    11 const movies = database.collection("movies");
    12
    13 const query = [
    14 {
    15 $search: {
    16 compound: {
    17 must: [
    18 {
    19 text: {
    20 query: "baseball",
    21 path: "plot",
    22 }
    23 }
    24 ],
    25 mustNot: [
    26 {
    27 text: {
    28 query: ["Comedy", "Romance"],
    29 path: "genres",
    30 },
    31 }
    32 ]
    33 }
    34 }
    35 },
    36 {
    37 $limit: 3
    38 },
    39 {
    40 $project: {
    41 _id: 0,
    42 title: 1,
    43 plot: 1,
    44 genres: 1
    45 }
    46 }
    47 ];
    48
    49 const cursor = movies.aggregate(query);
    50 await cursor.forEach(doc => console.log(doc));
    51 } finally {
    52 await client.close();
    53 }
    54}
    55
    56main().catch(console.error);
  2. Specify the <connection-string>, then run the query:

    node run-query.js
    {
    plot: 'The story of the life and career of the famed baseball player, Lou Gehrig.',
    genres: [ 'Biography', 'Drama', 'Family' ],
    title: 'The Pride of the Yankees'
    }
    {
    plot: 'Babe Ruth becomes a baseball legend but is unheroic to those who know him.',
    genres: [ 'Biography', 'Drama', 'Sport' ],
    title: 'The Babe'
    }
    {
    plot: 'Dominican baseball star Miguel "Sugar" Santos is recruited to play in the U.S. minor-leagues.',
    genres: [ 'Drama', 'Sport' ],
    title: 'Sugar'
    }
3

Atlas Search provides several search options that you can use to further process your Atlas Search query results. Add the sort option to your query to display the results in a specific order.

  1. Modify run-query.js to add the sort option.

    This query has the following search criteria:

    • The plot field must contain the word baseball.

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

    • Sort the results by the released date field in descending order. Atlas Search returns the most recent movies first.

    • $limit and $project stages to return only 3 documents and the title, plot, genres, and released fields.

    1const { MongoClient } = require("mongodb");
    2
    3async function main() {
    4 // Replace the placeholder with your connection string
    5 const uri = "<connection-string>";
    6 const client = new MongoClient(uri);
    7
    8 try {
    9 await client.connect();
    10 const database = client.db("sample_mflix");
    11 const movies = database.collection("movies");
    12
    13 const query = [
    14 {
    15 $search: {
    16 compound: {
    17 must: [
    18 {
    19 text: {
    20 query: "baseball",
    21 path: "plot",
    22 }
    23 }
    24 ],
    25 mustNot: [
    26 {
    27 text: {
    28 query: ["Comedy", "Romance"],
    29 path: "genres",
    30 }
    31 }
    32 ]
    33 },
    34 sort: {
    35 released: -1
    36 }
    37 }
    38 },
    39 {
    40 $limit: 3
    41 },
    42 {
    43 $project: {
    44 _id: 0,
    45 title: 1,
    46 plot: 1,
    47 genres: 1,
    48 released: 1
    49 }
    50 }
    51 ];
    52
    53 const cursor = movies.aggregate(query);
    54 await cursor.forEach(doc => console.log(doc));
    55 } finally {
    56 await client.close();
    57 }
    58}
    59
    60main().catch(console.error);
  2. Specify the <connection-string>, then run the query:

    node run-query.js
    {
    plot: 'A sports agent stages an unconventional recruitment strategy to get talented Indian cricket players to play Major League Baseball.',
    genres: [ 'Biography', 'Drama', 'Sport' ],
    title: 'Million Dollar Arm',
    released: 2014-05-16T00:00:00.000Z
    }
    {
    plot: 'A Taiwanese high school baseball team travels to Japan in 1931 to compete in a national tournament.',
    genres: [ 'Biography', 'Drama', 'History' ],
    title: 'Kano',
    released: 2014-02-27T00:00:00.000Z
    }
    {
    plot: "12-year-old Josh is a mixed race boy and a promising baseball player...",
    genres: [ 'Drama' ],
    title: 'Calloused Hands',
    released: 2013-03-03T00:00:00.000Z
    }
1

Run a basic $search query by using the text operator.

  1. Create a new file named run_query.py and paste the following code.

    This query has the following search criteria:

    • The plot field must contain the word baseball.

    • $limit and $project stages to return only 3 documents and the title and plot fields.

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

    python run_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'}
2

Atlas Search provides several operators that you can use to build complex queries and retrieve more specific results for your use case. Update your $search query to use the compound operator to combine multiple operators into a single query.

  1. Modify run_query.py to use the compound query.

    This query has the following search criteria:

    • The plot field must contain the word baseball.

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

    • $limit and $project stages to return only 3 documents and the title, plot, and genres fields.

    1import pymongo
    2
    3client = pymongo.MongoClient('<connection-string>')
    4result = client['sample_mflix']['movies'].aggregate([
    5 {
    6 '$search': {
    7 'compound': {
    8 'must': [
    9 {
    10 'text': {
    11 'query': 'baseball',
    12 'path': 'plot'
    13 }
    14 }
    15 ],
    16 'mustNot': [
    17 {
    18 'text': {
    19 'query': ['Comedy', 'Romance'],
    20 'path': 'genres'
    21 }
    22 }
    23 ]
    24 }
    25 }
    26 },
    27 {
    28 '$limit': 3
    29 },
    30 {
    31 '$project': {
    32 '_id': 0,
    33 'title': 1,
    34 'plot': 1,
    35 'genres': 1
    36 }
    37 }
    38])
    39
    40for i in result:
    41 print(i)
  2. Specify the <connection-string>, then run the query:

    python run_query.py
    {'plot': 'The story of the life and career of the famed baseball player, Lou Gehrig.', 'genres': ['Biography', 'Drama', 'Family'], 'title': 'The Pride of the Yankees'}
    {'plot': 'Babe Ruth becomes a baseball legend but is unheroic to those who know him.', 'genres': ['Biography', 'Drama', 'Sport'], 'title': 'The Babe'}
    {'plot': 'Dominican baseball star Miguel "Sugar" Santos is recruited to play in the U.S. minor-leagues.', 'genres': ['Drama', 'Sport'], 'title': 'Sugar'}
3

Atlas Search provides several search options that you can use to further process your Atlas Search query results. Add the sort option to your query to display the results in a specific order.

  1. Modify run_query.py to add the sort option.

    This query has the following search criteria:

    • The plot field must contain the word baseball.

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

    • Sort the results by the released date field in descending order. Atlas Search returns the most recent movies first.

    • $limit and $project stages to return only 3 documents and the title, plot, genres, and released fields.

    1import pymongo
    2
    3client = pymongo.MongoClient('<connection-string>')
    4result = client['sample_mflix']['movies'].aggregate([
    5 {
    6 '$search': {
    7 'compound': {
    8 'must': [
    9 {
    10 'text': {
    11 'query': 'baseball',
    12 'path': 'plot'
    13 }
    14 }
    15 ],
    16 'mustNot': [
    17 {
    18 'text': {
    19 'query': ['Comedy', 'Romance'],
    20 'path': 'genres'
    21 }
    22 }
    23 ]
    24 },
    25 'sort': {
    26 'released': -1
    27 }
    28 }
    29 },
    30 {
    31 '$limit': 3
    32 },
    33 {
    34 '$project': {
    35 '_id': 0,
    36 'title': 1,
    37 'plot': 1,
    38 'genres': 1,
    39 'released': 1
    40 }
    41 }
    42])
    43
    44for i in result:
    45 print(i)
  2. Specify the <connection-string>, then run the query:

    python run_query.py
    {'plot': 'A sports agent stages an unconventional recruitment strategy to get talented Indian cricket players to play Major League Baseball.', 'genres': ['Biography', 'Drama', 'Sport'], 'title': 'Million Dollar Arm', 'released': datetime.datetime(2014, 5, 16, 0, 0)}
    {'plot': 'A Taiwanese high school baseball team travels to Japan in 1931 to compete in a national tournament.', 'genres': ['Biography', 'Drama', 'History'], 'title': 'Kano', 'released': datetime.datetime(2014, 2, 27, 0, 0)}
    {'plot': "12-year-old Josh is a mixed race boy and a promising baseball player...", 'genres': ['Drama'], 'title': 'Calloused Hands', 'released': datetime.datetime(2013, 3, 3, 0, 0)}

You can use Atlas Search to run autocomplete and partial queries that return results for partial words. This is useful to retrieve results with increasing accuracy as more characters are entered in your application's search field. You must index the fields as the Atlas Search autocomplete type to use the autocomplete operator.

To get started, see How to Run Autocomplete and Partial Match Atlas Search Queries.

You can use Atlas Search to run facet queries that group search results by string, date, or numeric values. You must create an index with a facet definition to use the facet collector.

To get started, see How to Use Facets with Atlas Search.

Atlas Search allows you to sort the results in ascending or descending order on indexed boolean, date, number, objectId and string field values. To learn more, see Sort Atlas Search Results.

To learn more about Atlas Search, you can take Unit 1 of the Atlas Search Course on MongoDB University. The 2.25 hour unit includes an overview of Atlas Search and lessons on how to create Atlas Search indexes, use $search with different operators, and generate search facets.

You can also watch the following videos to learn more about Atlas Search:

Back

Atlas Search