Join us Sept 17 at .local NYC! Use code WEB50 to save 50% on tickets. Learn more >
MongoDB Event
Docs 菜单
Docs 主页
/
Atlas
/

Atlas Search 快速入门

Atlas Search 是 MongoDB Atlas 中内置的全文搜索解决方案,为构建基于相关性的应用功能提供了无缝且可扩展的体验。本快速入门指南描述了如何按照以下步骤开始:

  1. 在示例集合上创建 Atlas Search 索引。

  2. 构建 Atlas Search 查询以搜索集合。您将了解如何:

    • 运行基本查询以在字段中搜索术语

    • 使用操作符来优化您的搜索

    • 添加一个搜索选项以处理您的结果

所需时间:15 分钟

注意

本教程包括一些客户端的示例。有关所有支持的客户端,请参阅索引查询页面。

在本节中,您将为示例movies集合创建 Atlas Search 索引。您可以在 Atlas 集群或托管在本地计算机上的部署中创建 Atlas Search 索引。

1
  1. 创建免费的 Atlas 帐户或登录现有帐户。

  2. 如果您还没有 Atlas 集群,可以免费创建一个 M0 集群。要了解有关创建 Atlas 集群的更多信息,请参阅创建集群。

    重要提示:如果您使用的是现有集群,则必须拥有 Atlas 项目的 Project Data Access Admin 或更高的访问权限

    如果创建新集群,则默认拥有必要的权限。

    每个项目只能创建一个 M0 免费集群。

  3. 如果您尚未将本快速入门的示例数据集加载到您的集群,请将 sample_mflix 示例数据库加载到您的集群。

    如果您已加载 sample_mflix 数据集,请检查 sample_mflix 数据库是否包含 embedded_movies 集合。如果没有,请删除 sample_mflix 数据库并重新加载 sample_mflix 数据集。

    加载样本数据集可能需要几分钟才能完成。

  4. 在左侧边栏,单击Atlas Search。从 Select data source 菜单中选择您的集群,然后单击 Go to Atlas Search

2

➤ 使用 Select your language(选择您的语言)下拉菜单设置本教程的客户端。


  1. 示例数据加载完成后,单击 Create Search Index

  2. 在页面上进行以下选择,然后单击 Next

    Search Type

    选择 Atlas Search 索引类型。

    Index Name and Data Source

    指定以下信息:

    • 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. 定义索引。

    以下索引定义动态索引 movies 集合中的字段。

    查看 movies 集合的 "default" 索引定义。

    1. 查看索引定义。

      索引定义应类似于以下内容:

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

      上述索引定义对 movies 集合中每个文档中的支持类型字段动态创建索引。

    2. 单击 Next(连接)。

  4. 单击 Create Search Index(连接)。

  5. 等待索引完成构建。

    构建索引大约需要一分钟时间。在构建时,Status 列显示 Build in Progress。构建完成后,Status 列显示 Active

  1. 使用 mongosh 连接到 Atlas 集群。

    在终端窗口中打开 mongosh 并连接到 Atlas 集群。有关连接的详细说明,请参阅通过 mongosh 连接

  2. 切换到包含要创建索引的集合的数据库。

    例子

    use sample_mflix
    switched to db sample_mflix
  3. 运行 db.collection.createSearchIndex() 方法来创建索引。

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

打开Compass并连接到您的Atlas 集群。有关详细说明,请参阅通过Compass连接到集群。

2

Database 屏幕上,依次单击 sample_mflix 数据库和 movies 集合。

3
  1. 单击 Indexes 标签页,然后选择 Search Indexes

  2. 单击 Create Index,打开索引创建对话框。

  3. 使用默认索引名称和定义。

    1{
    2 mappings: {
    3 dynamic: true,
    4 },
    5}
  4. 单击 Create Search Index(连接)。

  1. 设置并初始化 .NET/C# 项目。

    # 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

    有关更详细的安装说明,请参阅 MongoDB C# 驱动程序文档。

  2. 定义索引。

    将以下代码粘贴到 Program.cs 文件中。

    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);

    <connection-string> 替换为Atlas 集群或本地Atlas部署的连接字符串。

    连接字符串应使用以下格式:

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

    要学习;了解更多信息,请参阅通过驱动程序连接到集群。

    连接字符串应使用以下格式:

    mongodb://localhost:<port-number>/?directConnection=true

    要学习;了解更多信息,请参阅连接字符串。

    连接字符串应使用以下格式:

    mongodb://localhost:<port-number>/?directConnection=true
  3. 创建索引。

    dotnet run Program.cs
    default
  1. 设置并初始化 Go 模块。

    # 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

    有关更详细的安装说明,请参阅 MongoDB Go 驱动程序文档。

  2. 定义索引。

    将以下代码粘贴到名为 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}

    <connection-string> 替换为Atlas 集群或本地Atlas部署的连接字符串。

    连接字符串应使用以下格式:

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

    要学习;了解更多信息,请参阅通过驱动程序连接到集群。

    连接字符串应使用以下格式:

    mongodb://localhost:<port-number>/?directConnection=true

    要学习;了解更多信息,请参阅连接字符串。

    连接字符串应使用以下格式:

    mongodb://localhost:<port-number>/?directConnection=true
  3. 创建索引。

    go run create-index.go
  1. 将 Java 驱动程序版本 4.11 或更高版本作为依赖项添加到您的 Java 项目中。根据您的包管理器,选择以下标签页之一:

    如果使用 Maven,请将以下依赖项添加到项目的 pom.xml文件的 dependencies大量中:

    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>

    如果您使用 Gradle,请将以下内容添加到项目 build.gradle文件的 dependencies大量中:

    build.gradle
    dependencies {
    // MongoDB Java Sync Driver v4.11.0 or later
    implementation 'org.mongodb:mongodb-driver-sync:[4.11.0,)'
    }
  2. 运行包管理器以安装项目的依赖项。

    有关更详细的安装说明和版本兼容性信息,请参阅 MongoDB Java 驱动程序文档。

  3. 定义索引。

    将以下示例粘贴到名为 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}

    <connection-string> 替换为Atlas 集群或本地Atlas部署的连接字符串。

    连接字符串应使用以下格式:

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

    要学习;了解更多信息,请参阅通过驱动程序连接到集群。

    连接字符串应使用以下格式:

    mongodb://localhost:<port-number>/?directConnection=true

    要学习;了解更多信息,请参阅连接字符串。

    连接字符串应使用以下格式:

    mongodb://localhost:<port-number>/?directConnection=true
  1. 安装 MongoDB Kotlin 协程驱动程序。

    创建一个新的 Kotlin 项目并安装 MongoDB Kotlin 协程驱动程序文档

  2. 定义索引。

    创建一个名为 CreateIndex.kt 的文件。将以下代码复制并粘贴到文件中。

    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}

    <connection-string> 替换为Atlas 集群或本地Atlas部署的连接字符串。

    连接字符串应使用以下格式:

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

    要学习;了解更多信息,请参阅通过驱动程序连接到集群。

    连接字符串应使用以下格式:

    mongodb://localhost:<port-number>/?directConnection=true

    要学习;了解更多信息,请参阅连接字符串。

    连接字符串应使用以下格式:

    mongodb://localhost:<port-number>/?directConnection=true
  3. 在 IDE 中运行 CreateIndex.kt文件。

  1. 初始化您的 Node.js 项目。

    # 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

    有关详细安装说明,请参阅 MongoDB Node 驱动程序文档

  2. 定义索引。

    将以下代码粘贴到名为 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);

    <connection-string> 替换为Atlas 集群或本地Atlas部署的连接字符串。

    连接字符串应使用以下格式:

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

    要学习;了解更多信息,请参阅通过驱动程序连接到集群。

    连接字符串应使用以下格式:

    mongodb://localhost:<port-number>/?directConnection=true

    要学习;了解更多信息,请参阅连接字符串。

    连接字符串应使用以下格式:

    mongodb://localhost:<port-number>/?directConnection=true
  3. 创建索引。

    node create-index.js
    default
  1. 安装 MongoDB 的 Python 驱动程序。

    pip install pymongo

    有关详细安装说明,请参阅 MongoDB Python 驱动程序 (PyMongo)

  2. 定义索引。

    将以下代码粘贴到名为 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)

    <connection-string> 替换为Atlas 集群或本地Atlas部署的连接字符串。

    连接字符串应使用以下格式:

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

    要学习;了解更多信息,请参阅通过驱动程序连接到集群。

    连接字符串应使用以下格式:

    mongodb://localhost:<port-number>/?directConnection=true

    要学习;了解更多信息,请参阅连接字符串。

    连接字符串应使用以下格式:

    mongodb://localhost:<port-number>/?directConnection=true
  3. 创建索引。

    python create_index.py
    default
  1. 初始化您的Rust项目。

    # Create a new Rust project
    cargo new atlas-search-quickstart && cd atlas-search-quickstart

    将以下依赖项添加到您的 Cargo.toml文件中:

    [dependencies]
    serde = "1.0"
    futures = "0.3"
    tokio = {version = "1.0", features = ["full"]}
    [dependencies.mongodb]
    version = "3.0"

    有关详细的安装说明,请参阅MongoDB Rust驱动程序下载和安装指南。

  2. 定义索引。

    将以下代码粘贴到 src/main.rs 中。

    src/main.rs
    1use mongodb::bson::{doc, Document};
    2use mongodb::{Client, Collection, SearchIndexModel, SearchIndexType};
    3
    4#[tokio::main]
    5async fn main() -> mongodb::error::Result<()> {
    6 // Connects to your Atlas deployment
    7 let uri =
    8 "<connection-string>";
    9
    10 let client = Client::with_uri_str(uri).await?;
    11
    12 // Sets the namespace
    13 let collection: Collection<Document> = client
    14 .database("sample_mflix")
    15 .collection("movies");
    16
    17 // Defines your Atlas Search index
    18 let index = doc! {
    19 "mappings": doc! {
    20 "dynamic": true
    21 }
    22 };
    23
    24 let idx_model = SearchIndexModel::builder()
    25 .definition(index)
    26 .name("search_idx".to_string())
    27 .index_type(SearchIndexType::Search)
    28 .build();
    29
    30 // Runs the helper method
    31 let result = collection.create_search_index(idx_model).await?;
    32 println!("{}", result);
    33
    34 Ok(())
    35}

    <connection-string> 替换为Atlas 集群或本地Atlas部署的连接字符串。

    连接字符串应使用以下格式:

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

    要学习;了解更多信息,请参阅通过驱动程序连接到集群。

    连接字符串应使用以下格式:

    mongodb://localhost:<port-number>/?directConnection=true

    要学习;了解更多信息,请参阅连接字符串。

    连接字符串应使用以下格式:

    mongodb://localhost:<port-number>/?directConnection=true
  3. 创建索引。

    cargo run
    search_idx
1
  1. 安装Atlas CLI。

    如果使用 Homebrew ,则可以在终端中运行以下命令:

    brew install mongodb-atlas-cli

    有关其他操作系统上的安装说明,请参阅安装Atlas CLI

  2. 安装 Docker。

    Docker需要网络连接来拉取和缓存MongoDB映像。

  3. 安装 MongoDB Database Tools。

    您必须安装 MongoDB 命令行 Database Tools 才能访问 mongorestore 命令,您将使用该命令加载示例数据。

2
  1. 如果没有 Atlas 账户,请在终端运行 atlas setup创建新帐户

  2. 运行 atlas deployments setup 并按照提示创建本地部署。当系统提示连接到部署时,选择 skip

    有关详细说明,请参阅创建本地 Atlas 部署。

3
  1. 在终端中运行以下命令以下载示例数据:

    curl https://atlas-education.s3.amazonaws.com/sampledata.archive -o sampledata.archive
  2. 运行以下命令将数据加载到部署中,将 <port-number> 替换为托管部署的端口:

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

➤ 使用 Select your language(选择您的语言)下拉菜单设置本教程的客户端。


  1. 示例数据加载完成后,单击 Create Search Index

  2. 在页面上进行以下选择,然后单击 Next

    Search Type

    选择 Atlas Search 索引类型。

    Index Name and Data Source

    指定以下信息:

    • 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. 定义索引。

    以下索引定义动态索引 movies 集合中的字段。

    查看 movies 集合的 "default" 索引定义。

    1. 查看索引定义。

      索引定义应类似于以下内容:

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

      上述索引定义对 movies 集合中每个文档中的支持类型字段动态创建索引。

    2. 单击 Next(连接)。

  4. 单击 Create Search Index(连接)。

  5. 等待索引完成构建。

    构建索引大约需要一分钟时间。在构建时,Status 列显示 Build in Progress。构建完成后,Status 列显示 Active

  1. 使用 mongosh 连接到 Atlas 集群。

    在终端窗口中打开 mongosh 并连接到 Atlas 集群。有关连接的详细说明,请参阅通过 mongosh 连接

  2. 切换到包含要创建索引的集合的数据库。

    例子

    use sample_mflix
    switched to db sample_mflix
  3. 运行 db.collection.createSearchIndex() 方法来创建索引。

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

打开Compass并连接到您的Atlas 集群。有关详细说明,请参阅通过Compass连接到集群。

2

Database 屏幕上,依次单击 sample_mflix 数据库和 movies 集合。

3
  1. 单击 Indexes 标签页,然后选择 Search Indexes

  2. 单击 Create Index,打开索引创建对话框。

  3. 指定索引的名称。

    您的 Atlas Search 索引默认名为 default。如果保留此名称,则对于任何未在其操作符中指定不同 index选项的 Atlas Search 查询,您的搜索索引将成为默认搜索索引。如果您要创建多个索引,我们建议您在所有索引中保持一致且具有描述性的命名规则。

  4. 指定 JSON Atlas Search 索引定义。

    1{
    2 "mappings": {
    3 "dynamic": true|false,
    4 "fields": {
    5 "<field-name>": {
    6 "type": "string"
    7 }
    8 }
    9 }
    10}
  5. 单击 Create Search Index(连接)。

  1. 设置并初始化 .NET/C# 项目。

    # 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

    有关更详细的安装说明,请参阅 MongoDB C# 驱动程序文档。

  2. 定义索引。

    将以下代码粘贴到 Program.cs 文件中。

    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);

    <connection-string> 替换为Atlas 集群或本地Atlas部署的连接字符串。

    连接字符串应使用以下格式:

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

    要学习;了解更多信息,请参阅通过驱动程序连接到集群。

    连接字符串应使用以下格式:

    mongodb://localhost:<port-number>/?directConnection=true

    要学习;了解更多信息,请参阅连接字符串。

    连接字符串应使用以下格式:

    mongodb://localhost:<port-number>/?directConnection=true
  3. 创建索引。

    dotnet run Program.cs
    default
  1. 设置并初始化 Go 模块。

    # 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

    有关更详细的安装说明,请参阅 MongoDB Go 驱动程序文档。

  2. 定义索引。

    将以下代码粘贴到名为 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}

    <connection-string> 替换为Atlas 集群或本地Atlas部署的连接字符串。

    连接字符串应使用以下格式:

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

    要学习;了解更多信息,请参阅通过驱动程序连接到集群。

    连接字符串应使用以下格式:

    mongodb://localhost:<port-number>/?directConnection=true

    要学习;了解更多信息,请参阅连接字符串。

    连接字符串应使用以下格式:

    mongodb://localhost:<port-number>/?directConnection=true
  3. 创建索引。

    go run create-index.go
  1. 将 Java 驱动程序版本 4.11 或更高版本作为依赖项添加到您的 Java 项目中。根据您的包管理器,选择以下标签页之一:

    如果使用 Maven,请将以下依赖项添加到项目的 pom.xml文件的 dependencies大量中:

    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>

    如果您使用 Gradle,请将以下内容添加到项目 build.gradle文件的 dependencies大量中:

    build.gradle
    dependencies {
    // MongoDB Java Sync Driver v4.11.0 or later
    implementation 'org.mongodb:mongodb-driver-sync:[4.11.0,)'
    }
  2. 运行包管理器以安装项目的依赖项。

    有关更详细的安装说明和版本兼容性信息,请参阅 MongoDB Java 驱动程序文档。

  3. 定义索引。

    将以下示例粘贴到名为 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}

    <connection-string> 替换为Atlas 集群或本地Atlas部署的连接字符串。

    连接字符串应使用以下格式:

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

    要学习;了解更多信息,请参阅通过驱动程序连接到集群。

    连接字符串应使用以下格式:

    mongodb://localhost:<port-number>/?directConnection=true

    要学习;了解更多信息,请参阅连接字符串。

    连接字符串应使用以下格式:

    mongodb://localhost:<port-number>/?directConnection=true
  1. 安装 MongoDB Kotlin 协程驱动程序。

    创建一个新的 Kotlin 项目并安装 MongoDB Kotlin 协程驱动程序文档

  2. 定义索引。

    创建一个名为 CreateIndex.kt 的文件。将以下代码复制并粘贴到文件中。

    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}

    <connection-string> 替换为Atlas 集群或本地Atlas部署的连接字符串。

    连接字符串应使用以下格式:

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

    要学习;了解更多信息,请参阅通过驱动程序连接到集群。

    连接字符串应使用以下格式:

    mongodb://localhost:<port-number>/?directConnection=true

    要学习;了解更多信息,请参阅连接字符串。

    连接字符串应使用以下格式:

    mongodb://localhost:<port-number>/?directConnection=true
  3. 在 IDE 中运行 CreateIndex.kt文件。

  1. 初始化您的 Node.js 项目。

    # 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

    有关详细安装说明,请参阅 MongoDB Node 驱动程序文档

  2. 定义索引。

    将以下代码粘贴到名为 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);

    <connection-string> 替换为Atlas 集群或本地Atlas部署的连接字符串。

    连接字符串应使用以下格式:

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

    要学习;了解更多信息,请参阅通过驱动程序连接到集群。

    连接字符串应使用以下格式:

    mongodb://localhost:<port-number>/?directConnection=true

    要学习;了解更多信息,请参阅连接字符串。

    连接字符串应使用以下格式:

    mongodb://localhost:<port-number>/?directConnection=true
  3. 创建索引。

    node create-index.js
    default
  1. 安装 MongoDB 的 Python 驱动程序。

    pip install pymongo

    有关详细安装说明,请参阅 MongoDB Python 驱动程序 (PyMongo)

  2. 定义索引。

    将以下代码粘贴到名为 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)

    <connection-string> 替换为Atlas 集群或本地Atlas部署的连接字符串。

    连接字符串应使用以下格式:

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

    要学习;了解更多信息,请参阅通过驱动程序连接到集群。

    连接字符串应使用以下格式:

    mongodb://localhost:<port-number>/?directConnection=true

    要学习;了解更多信息,请参阅连接字符串。

    连接字符串应使用以下格式:

    mongodb://localhost:<port-number>/?directConnection=true
  3. 创建索引。

    python create_index.py
    default
  1. 初始化您的Rust项目。

    # Create a new Rust project
    cargo new atlas-search-quickstart && cd atlas-search-quickstart

    将以下依赖项添加到您的 Cargo.toml文件中:

    [dependencies]
    serde = "1.0"
    futures = "0.3"
    tokio = {version = "1.0", features = ["full"]}
    [dependencies.mongodb]
    version = "3.0"

    有关详细的安装说明,请参阅MongoDB Rust驱动程序下载和安装指南。

  2. 定义索引。

    将以下代码粘贴到 src/main.rs 中。

    src/main.rs
    1use mongodb::bson::{doc, Document};
    2use mongodb::{Client, Collection, SearchIndexModel, SearchIndexType};
    3
    4#[tokio::main]
    5async fn main() -> mongodb::error::Result<()> {
    6 // Connects to your Atlas deployment
    7 let uri =
    8 "<connection-string>";
    9
    10 let client = Client::with_uri_str(uri).await?;
    11
    12 // Sets the namespace
    13 let collection: Collection<Document> = client
    14 .database("sample_mflix")
    15 .collection("movies");
    16
    17 // Defines your Atlas Search index
    18 let index = doc! {
    19 "mappings": doc! {
    20 "dynamic": true
    21 }
    22 };
    23
    24 let idx_model = SearchIndexModel::builder()
    25 .definition(index)
    26 .name("search_idx".to_string())
    27 .index_type(SearchIndexType::Search)
    28 .build();
    29
    30 // Runs the helper method
    31 let result = collection.create_search_index(idx_model).await?;
    32 println!("{}", result);
    33
    34 Ok(())
    35}

    <connection-string> 替换为Atlas 集群或本地Atlas部署的连接字符串。

    连接字符串应使用以下格式:

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

    要学习;了解更多信息,请参阅通过驱动程序连接到集群。

    连接字符串应使用以下格式:

    mongodb://localhost:<port-number>/?directConnection=true

    要学习;了解更多信息,请参阅连接字符串。

    连接字符串应使用以下格式:

    mongodb://localhost:<port-number>/?directConnection=true
  3. 创建索引。

    cargo run
    search_idx

在本节中,您将对已创建索引的集合运行查询。

1

您可以从侧边栏、 Data Explorer 或集群详细信息页面转到 Atlas Search 页面。

  1. 在侧边栏中,单击 Services 标题下的 Atlas Search

    如果没有集群,则请单击 Create cluster 来创建一个。要了解更多信息,请参阅创建集群

  2. 如果您的项目有多个集群,请从 Select cluster 下拉列表中选择要使用的集群,然后单击 Go to Atlas Search

    将显示 Atlas Search 页面。

  1. 单击集群的对应 Browse Collections 按钮。

  2. 展开数据库并选择集合。

  3. 单击该集合的 Search Indexes 标签页。

    将显示 Atlas Search 页面。

  1. 单击集群的名称。

  2. 单击 Atlas Search 标签页。

    将显示 Atlas Search 页面。

2

单击要查询的索引右侧的 Query 按钮。

3

单击 Edit Query 以查看 JSON 格式的默认查询语法示例。

4

使用 text 操作符运行基本的 $search 查询。

此查询具有以下搜索条件:

  • plot 字段必须包含 baseball 词项。

将以下查询粘贴到 Query Editor 中,然后点击 Query Editor 中的 Search 按钮。

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

注意

Search Tester 可能不会显示其所返回文档的所有字段。要查看所有字段,包括在查询路径中指定的字段,请展开结果中的文档。

5

Atlas Search 提供了多种操作符,您可以使用它们来构建复杂的查询,并为您的使用案例检索更具体的结果。更新您的 $search 查询以使用复合操作符将多个操作符组合到一个查询中。

此查询具有以下搜索条件:

  • plot 字段必须包含 baseball 词项。

  • genres 字段不得包含 ComedyRomance

将以下查询粘贴到 Query Editor 中,然后点击 Query Editor 中的 Search 按钮。

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 提供了多个搜索选项,您可以使用这些选项来进一步处理 Atlas Search 查询结果。将 sort 选项添加到您的查询中,以特定顺序显示结果。

此查询具有以下搜索条件:

  • plot 字段必须包含 baseball 词项。

  • genres 字段不得包含 ComedyRomance

  • released 日期字段以降序排列结果。Atlas Search 会优先返回最新的电影。

将以下查询复制并粘贴到 Query Editor 中,然后点击 Query Editor 中的 Search 按钮。

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

使用 text 操作符运行基本的 $search 查询。

此查询具有以下搜索条件:

  • plot 字段必须包含 baseball 词项。

  • $limit$project 阶段仅返回 3 个文档以及 titleplot 字段。

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 提供了多种操作符,您可以使用它们来构建复杂的查询,并为您的使用案例检索更具体的结果。更新您的 $search 查询以使用复合操作符将多个操作符组合到一个查询中。

此查询具有以下搜索条件:

  • plot 字段必须包含 baseball 词项。

  • genres 字段不得包含 ComedyRomance

  • $limit$project 阶段仅返回 3 个文档以及 titleplotgenres 字段。

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 提供了多个搜索选项,您可以使用这些选项来进一步处理 Atlas Search 查询结果。将 sort 选项添加到您的查询中,以特定顺序显示结果。

此查询具有以下搜索条件:

  • plot 字段必须包含 baseball 词项。

  • genres 字段不得包含 ComedyRomance

  • released 日期字段以降序排列结果。Atlas Search 会优先返回最新的电影。

  • $limit$project 阶段仅返回 3 个文档以及 titleplotgenresreleased 字段。

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

Database 屏幕上,依次单击 sample_mflix 数据库和 movies 集合。

2

使用 text 操作符运行基本的 $search 查询。

若要在 MongoDB Compass 中运行此查询:

  1. 单击 Aggregations 标签页。

  2. 单击 Select...,然后从下拉菜单中选择阶段并为该阶段添加查询,以配置以下每个管道阶段。单击 Add Stage 以添加其他阶段。

    此查询具有以下搜索条件:

    • plot 字段必须包含 baseball 词项。

    • $limit$project 阶段仅返回 3 个文档以及 titleplot 字段。

    管道阶段
    查询

    $search

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

    $limit

    3

    $project

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

如果启用了 Auto Preview,MongoDB Compass 将在 $project 管道阶段旁边显示以下文档:

{
"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 提供了多种操作符,您可以使用它们来构建复杂的查询,并为您的使用案例检索更具体的结果。更新您的 $search 查询以使用复合操作符将多个操作符组合到一个查询中。

此查询具有以下搜索条件:

  • plot 字段必须包含 baseball 词项。

  • genres 字段不得包含 ComedyRomance

  • $limit$project 阶段仅返回 3 个文档以及 titleplotgenres 字段。

在 MongoDB Compass 中更新以下管道阶段:

管道阶段
查询

$search

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

$project

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

如果启用了 Auto Preview,MongoDB Compass 将在 $project 管道阶段旁边显示以下文档:

{
"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 提供了多个搜索选项,您可以使用这些选项来进一步处理 Atlas Search 查询结果。将 sort 选项添加到您的查询中,以特定顺序显示结果。

此查询具有以下搜索条件:

  • plot 字段必须包含 baseball 词项。

  • genres 字段不得包含 ComedyRomance

  • released 日期字段以降序排列结果。Atlas Search 会优先返回最新的电影。

  • $limit$project 阶段仅返回 3 个文档以及 titleplotgenresreleased 字段。

在 MongoDB Compass 中更新以下管道阶段:

管道阶段
查询

$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,
}

如果启用了 Auto Preview,MongoDB Compass 将在 $project 管道阶段旁边显示以下文档:

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

使用 text 操作符运行基本的 $search 查询。

  1. Program.cs文件的内容替换为以下代码。

    此查询具有以下搜索条件:

    • plot 字段必须包含 baseball 词项。

    • $limit$project 阶段仅返回 3 个文档以及 titleplot 字段。

    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. 指定 <connection-string>,然后运行查询:

    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 提供了多种操作符,您可以使用它们来构建复杂的查询,并为您的使用案例检索更具体的结果。更新您的 $search 查询以使用复合操作符将多个操作符组合到一个查询中。

  1. 使用以下代码修改您的 Program.cs 文件。

    此查询具有以下搜索条件:

    • plot 字段必须包含 baseball 词项。

    • genres 字段不得包含 ComedyRomance

    • $limit$project 阶段仅返回 3 个文档以及 titleplotgenres 字段。

    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. 指定 <connection-string>,然后运行查询:

    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 提供了多个搜索选项,您可以使用这些选项来进一步处理 Atlas Search 查询结果。将 sort 选项添加到您的查询中,以特定顺序显示结果。

  1. 使用以下代码修改您的 Program.cs 文件。

    此查询具有以下搜索条件:

    • plot 字段必须包含 baseball 词项。

    • genres 字段不得包含 ComedyRomance

    • released 日期字段以降序排列结果。Atlas Search 会优先返回最新的电影。

    • $limit$project 阶段仅返回 3 个文档以及 titleplotgenresreleased 字段。

    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. 指定 <connection-string>,然后运行查询:

    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

使用 text 操作符运行基本的 $search 查询。

  1. 创建一个名为 run-query.go 的新文件并粘贴以下代码。

    此查询具有以下搜索条件:

    • plot 字段必须包含 baseball 词项。

    • $limit$project 阶段仅返回 3 个文档以及 titleplot 字段。

    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. 指定 <connection-string>,然后运行查询:

    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 提供了多种操作符,您可以使用它们来构建复杂的查询,并为您的使用案例检索更具体的结果。更新您的 $search 查询以使用复合操作符将多个操作符组合到一个查询中。

  1. 修改 run-query.go 以使用复合查询。

    此查询具有以下搜索条件:

    • plot 字段必须包含 baseball 词项。

    • genres 字段不得包含 ComedyRomance

    • $limit$project 阶段仅返回 3 个文档以及 titleplotgenres 字段。

    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. 指定 <connection-string>,然后运行查询:

    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 提供了多个搜索选项,您可以使用这些选项来进一步处理 Atlas Search 查询结果。将 sort 选项添加到您的查询中,以特定顺序显示结果。

  1. 修改run-query.go以添加 sort 选项。

    此查询具有以下搜索条件:

    • plot 字段必须包含 baseball 词项。

    • genres 字段不得包含 ComedyRomance

    • released 日期字段以降序排列结果。Atlas Search 会优先返回最新的电影。

    • $limit$project 阶段仅返回 3 个文档以及 titleplotgenresreleased 字段。

    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. 指定 <connection-string>,然后运行查询:

    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

确保 CLASSPATH 包含以下库。

junit

4.11.0 或更高版本

mongodb-driver-sync

4.11.0 或更高版本

slf4j-log4j12

1.7.30 或更高版本

有关更详细的安装说明和版本兼容性信息,请参阅 MongoDB Java 驱动程序文档。

2

使用 text 操作符运行基本的 $search 查询。

  1. 创建一个名为 RunQuery.java 的新文件并粘贴以下代码。

    此查询具有以下搜索条件:

    • plot 字段必须包含 baseball 词项。

    • $limit$project 阶段仅返回 3 个文档以及 titleplot 字段。

    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}

    注意

    要在 Maven 环境中运行示例代码,请在文件中的 import 语句上方添加以下内容。

    package com.mongodb.drivers;
  2. 指定 <connection-string>,然后运行查询:

    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 提供了多种操作符,您可以使用它们来构建复杂的查询,并为您的使用案例检索更具体的结果。更新您的 $search 查询以使用复合操作符将多个操作符组合到一个查询中。

  1. 修改 RunQuery.java 以使用复合查询。

    此查询具有以下搜索条件:

    • plot 字段必须包含 baseball 词项。

    • genres 字段不得包含 ComedyRomance

    • $limit$project 阶段仅返回 3 个文档以及 titleplotgenres 字段。

    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. 指定 <connection-string>,然后运行查询:

    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 提供了多个搜索选项,您可以使用这些选项来进一步处理 Atlas Search 查询结果。将 sort 选项添加到您的查询中,以特定顺序显示结果。

  1. 修改RunQuery.java以添加 sort 选项。

    此查询具有以下搜索条件:

    • plot 字段必须包含 baseball 词项。

    • genres 字段不得包含 ComedyRomance

    • released 日期字段以降序排列结果。Atlas Search 会优先返回最新的电影。

    • $limit$project 阶段仅返回 3 个文档以及 titleplotgenresreleased 字段。

    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. 指定 <connection-string>,然后运行查询:

    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

使用 text 操作符运行基本的 $search 查询。

  1. 创建一个名为 RunQuery.kt 的新文件并粘贴以下代码。

    此查询具有以下搜索条件:

    • plot 字段必须包含 baseball 词项。

    • $limit$project 阶段仅返回 3 个文档以及 titleplot 字段。

    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. 指定 <connection-string>,然后运行查询:

    当你在 IDE 中运行 RunQuery.kt 程序时,它会打印以下文档:

    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 提供了多种操作符,您可以使用它们来构建复杂的查询,并为您的使用案例检索更具体的结果。更新您的 $search 查询以使用复合操作符将多个操作符组合到一个查询中。

  1. 修改 RunQuery.kt 以使用复合查询。

    此查询具有以下搜索条件:

    • plot 字段必须包含 baseball 词项。

    • genres 字段不得包含 ComedyRomance

    • $limit$project 阶段仅返回 3 个文档以及 titleplotgenres 字段。

    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. 指定 <connection-string>,然后运行查询。

    当你在 IDE 中运行 RunQuery.kt 程序时,它会打印以下文档:

    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 提供了多个搜索选项,您可以使用这些选项来进一步处理 Atlas Search 查询结果。将 sort 选项添加到您的查询中,以特定顺序显示结果。

  1. 修改RunQuery.kt以添加 sort 选项。

    此查询具有以下搜索条件:

    • plot 字段必须包含 baseball 词项。

    • genres 字段不得包含 ComedyRomance

    • released 日期字段以降序排列结果。Atlas Search 会优先返回最新的电影。

    • $limit$project 阶段仅返回 3 个文档以及 titleplotgenresreleased 字段。

    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. 指定 <connection-string>,然后运行查询:

    当你在 IDE 中运行 RunQuery.kt 程序时,它会打印以下文档:

    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

使用 text 操作符运行基本的 $search 查询。

  1. 创建一个名为 run-query.js 的新文件并粘贴以下代码。

    此查询具有以下搜索条件:

    • plot 字段必须包含 baseball 词项。

    • $limit$project 阶段仅返回 3 个文档以及 titleplot 字段。

    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. 指定 <connection-string>,然后运行查询:

    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 提供了多种操作符,您可以使用它们来构建复杂的查询,并为您的使用案例检索更具体的结果。更新您的 $search 查询以使用复合操作符将多个操作符组合到一个查询中。

  1. 修改 run-query.js 以使用复合查询。

    此查询具有以下搜索条件:

    • plot 字段必须包含 baseball 词项。

    • genres 字段不得包含 ComedyRomance

    • $limit$project 阶段仅返回 3 个文档以及 titleplotgenres 字段。

    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. 指定 <connection-string>,然后运行查询:

    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 提供了多个搜索选项,您可以使用这些选项来进一步处理 Atlas Search 查询结果。将 sort 选项添加到您的查询中,以特定顺序显示结果。

  1. 修改run-query.js以添加 sort 选项。

    此查询具有以下搜索条件:

    • plot 字段必须包含 baseball 词项。

    • genres 字段不得包含 ComedyRomance

    • released 日期字段以降序排列结果。Atlas Search 会优先返回最新的电影。

    • $limit$project 阶段仅返回 3 个文档以及 titleplotgenresreleased 字段。

    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. 指定 <connection-string>,然后运行查询:

    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

使用 text 操作符运行基本的 $search 查询。

  1. 创建一个名为 run_query.py 的新文件并粘贴以下代码。

    此查询具有以下搜索条件:

    • plot 字段必须包含 baseball 词项。

    • $limit$project 阶段仅返回 3 个文档以及 titleplot 字段。

    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. 指定 <connection-string>,然后运行查询:

    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 提供了多种操作符,您可以使用它们来构建复杂的查询,并为您的使用案例检索更具体的结果。更新您的 $search 查询以使用复合操作符将多个操作符组合到一个查询中。

  1. 修改 run_query.py 以使用复合查询。

    此查询具有以下搜索条件:

    • plot 字段必须包含 baseball 词项。

    • genres 字段不得包含 ComedyRomance

    • $limit$project 阶段仅返回 3 个文档以及 titleplotgenres 字段。

    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. 指定 <connection-string>,然后运行查询:

    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 提供了多个搜索选项,您可以使用这些选项来进一步处理 Atlas Search 查询结果。将 sort 选项添加到您的查询中,以特定顺序显示结果。

  1. 修改run_query.py以添加 sort 选项。

    此查询具有以下搜索条件:

    • plot 字段必须包含 baseball 词项。

    • genres 字段不得包含 ComedyRomance

    • released 日期字段以降序排列结果。Atlas Search 会优先返回最新的电影。

    • $limit$project 阶段仅返回 3 个文档以及 titleplotgenresreleased 字段。

    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. 指定 <connection-string>,然后运行查询:

    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)}
1

使用 text 操作符运行基本的 $search 查询。

  1. 创建一个名为 src/main.rs 的新文件并粘贴以下代码。

    此查询具有以下搜索条件:

    • plot 字段必须包含 baseball 词项。

    • $limit$project 阶段仅返回 3 个文档以及 titleplot 字段。

    1use mongodb::bson::{doc, DateTime};
    2use mongodb::{Client, Collection};
    3use serde::{Deserialize, Serialize};
    4use futures::TryStreamExt;
    5
    6#[derive(Debug, Deserialize, Serialize)]
    7struct Movie {
    8 title: Option<String>,
    9 plot: Option<String>,
    10 genres: Option<Vec<String>>,
    11 released: Option<DateTime>,
    12}
    13
    14#[tokio::main]
    15async fn main() -> mongodb::error::Result<()> {
    16 // Replace the placeholder with your connection string
    17 let uri = "<connection-string>";
    18 let client = Client::with_uri_str(uri).await?;
    19
    20 let collection: Collection<Movie> = client
    21 .database("sample_mflix")
    22 .collection("movies");
    23
    24 let query = vec![
    25 doc! {
    26 "$search": {
    27 "index": "search_idx",
    28 "text": {
    29 "query": "baseball",
    30 "path": "plot"
    31 }
    32 }
    33 },
    34 doc! {
    35 "$limit": 3
    36 },
    37 doc! {
    38 "$project": {
    39 "_id": 0,
    40 "title": 1,
    41 "plot": 1
    42 }
    43 }
    44 ];
    45
    46 println!("Executing aggregation query...");
    47 let mut results = movies.aggregate(query).await?;
    48
    49 println!("Processing results...");
    50 while let Some(doc) = results.try_next().await? {
    51 let movie: Movie = mongodb::bson::from_document(doc)?;
    52 println!("{{ \"title\": {:?}, \"plot\": {:?} }}",
    53 movie.title.unwrap_or_else(|| "N/A".to_string()),
    54 movie.plot.unwrap_or_else(|| "N/A".to_string()));
    55 }
    56 Ok(())
    57}
  2. 指定 <connection-string>,然后运行查询:

    cargo run
    { "title": "The Benchwarmers", "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": "Ed", "plot": "A trained
    chimpanzee plays third base for a minor-league baseball team." }
    { "title": "Little Big League", "plot": "A young boy is
    bequeathed the ownership of a professional baseball team." }
2

Atlas Search 提供了多种操作符,您可以使用它们来构建复杂的查询,并为您的使用案例检索更具体的结果。更新您的 $search 查询以使用复合操作符将多个操作符组合到一个查询中。

  1. 修改 src/main.rs 以使用复合查询。

    此查询具有以下搜索条件:

    • plot 字段必须包含 baseball 词项。

    • genres 字段不得包含 ComedyRomance

    • $limit$project 阶段仅返回 3 个文档以及 titleplotgenres 字段。

    1use mongodb::bson::{doc, DateTime, from_document};
    2use mongodb::{Client, Collection};
    3use serde::{Deserialize, Serialize};
    4use futures::TryStreamExt;
    5
    6#[derive(Debug, Deserialize, Serialize)]
    7struct Movie {
    8 title: Option<String>,
    9 plot: Option<String>,
    10 genres: Option<Vec<String>>,
    11 released: Option<DateTime>,
    12}
    13
    14#[tokio::main]
    15async fn main() -> mongodb::error::Result<()> {
    16 // Replace the placeholder with your connection string
    17 let uri = "<connection-string>";
    18 let client = Client::with_uri_str(uri).await?;
    19
    20 let query = vec![
    21 doc! {
    22 "$search": {
    23 "index": "search_idx",
    24 "compound": {
    25 "must": [
    26 {
    27 "text": {
    28 "query": "baseball",
    29 "path": "plot"
    30 }
    31 }
    32 ],
    33 "mustNot": [
    34 {
    35 "text": {
    36 "query": ["Comedy", "Romance"],
    37 "path": "genres"
    38 }
    39 }
    40 ]
    41 }
    42 }
    43 },
    44 doc! {
    45 "$limit": 3
    46 },
    47 doc! {
    48 "$project": {
    49 "_id": 0,
    50 "title": 1,
    51 "plot": 1,
    52 "genres": 1
    53 }
    54 }
    55 ];
    56
    57 let movies: Collection<Movie> = client
    58 .database("sample_mflix")
    59 .collection("movies");
    60
    61 let mut result = collection.aggregate(query).await?;
    62
    63 while let Some(doc) = result.try_next().await? {
    64 let movie: Movie = from_document(doc)?;
    65 println!(" Title: '{}'", movie.title.unwrap_or_else(|| "N/A".to_string()));
    66 println!(" Plot: '{}'", movie.plot.unwrap_or_else(|| "N/A".to_string()));
    67 println!(" Genres: {:?}", movie.genres.unwrap_or_default());
    68 println!();
    69 }
    70 Ok(())
    71}
  2. 指定 <connection-string>,然后运行查询:

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

Atlas Search 提供了多个搜索选项,您可以使用这些选项来进一步处理 Atlas Search 查询结果。将 sort 选项添加到您的查询中,以特定顺序显示结果。

  1. 修改src/main.rs以添加 sort 选项。

    此查询具有以下搜索条件:

    • plot 字段必须包含 baseball 词项。

    • genres 字段不得包含 ComedyRomance

    • released 日期字段以降序排列结果。Atlas Search 会优先返回最新的电影。

    • $limit$project 阶段仅返回 3 个文档以及 titleplotgenresreleased 字段。

    1use mongodb::bson::{doc, DateTime, from_document};
    2use mongodb::{Client, Collection};
    3use serde::{Deserialize, Serialize};
    4use futures::TryStreamExt;
    5
    6#[derive(Debug, Deserialize, Serialize)]
    7struct Movie {
    8 title: Option<String>,
    9 plot: Option<String>,
    10 genres: Option<Vec<String>>,
    11 released: Option<DateTime>,
    12}
    13
    14#[tokio::main]
    15async fn main() -> mongodb::error::Result<()> {
    16 // Replace the placeholder with your connection string
    17 let uri = "<connection-string>";
    18 let client = Client::with_uri_str(uri).await?;
    19
    20 let query = vec![
    21 doc! {
    22 "$search": {
    23 "index": "search_idx",
    24 "compound": {
    25 "must": [
    26 {
    27 "text": {
    28 "query": "baseball",
    29 "path": "plot"
    30 }
    31 }
    32 ],
    33 "mustNot": [
    34 {
    35 "text": {
    36 "query": ["Comedy", "Romance"],
    37 "path": "genres"
    38 }
    39 }
    40 ]
    41 },
    42 "sort": {
    43 "released": -1
    44 }
    45 }
    46 },
    47 doc! {
    48 "$limit": 3
    49 },
    50 doc! {
    51 "$project": {
    52 "_id": 0,
    53 "title": 1,
    54 "plot": 1,
    55 "genres": 1,
    56 "released": 1
    57 }
    58 }
    59 ];
    60
    61 let movies: Collection<Movie> = client
    62 .database("sample_mflix")
    63 .collection("movies");
    64 let mut cursor = movies.aggregate(query).await?;
    65 while let Some(doc) = cursor.try_next().await? {
    66 let movie: Movie = from_document(doc)?;
    67 println!("Title: {:?}", movie.title.unwrap_or_else(|| "N/A".to_string()));
    68 println!("Plot: {:?}", movie.plot.unwrap_or_else(|| "N/A".to_string()));
    69 println!("Genres: {:?}", movie.genres.unwrap_or_default());
    70 if let Some(released) = movie.released {
    71 println!("Released: {:?}", released);
    72 }
    73 println!();
    74 }
    75
    76 Ok(())
    77}
  2. 指定 <connection-string>,然后运行查询:

    cargo run
    Title: "Million Dollar Arm"
    Plot: "A sports agent stages an unconventional recruitment strategy to get talented Indian cricket players to play Major League Baseball."
    Genres: ["Biography", "Drama", "Sport"]
    Released: DateTime(2014-05-16 0:00:00.0 +00:00:00)
    Title: "Kano"
    Plot: "A Taiwanese high school baseball team travels to Japan in 1931 to compete in a national tournament."
    Genres: ["Biography", "Drama", "History"]
    Released: DateTime(2014-02-27 0:00:00.0 +00:00:00)
    Title: "Calloused Hands"
    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"]
    Released: DateTime(2013-03-03 0:00:00.0 +00:00:00)

您可以使用 Atlas Search 来运行自动补全和部分匹配查询,以返回部分单词的结果。当您在应用程序搜索字段中输入更多字符时,这有助于提高检索结果的准确性。您必须将字段索引建立为 Atlas Search autocomplete 类型,才能使用 autocomplete 操作符。

要开始,请参阅如何运行自动补全和部分匹配 Atlas 搜索查询

您可以使用Atlas Search运行分面(Facet)查询,按字符串、日期或数值对搜索结果群组。 您必须创建带有分面(Facet)定义的索引,才能使用facet (Atlas Search Operator) 收集器。

要开始使用,请参阅如何在 Atlas Search 中使用分面

使用 Atlas Search Playground,您可以通过配置搜索索引并运行查询来尝试不同的 Atlas Search 功能,而无需 Atlas 帐户、集群或集合。

要了解更多信息,请参阅 Atlas Search Playground。

如要了解有关 Atlas Search 的更多信息,不妨学习 MongoDB University 上的 Atlas Search 课程的第 1 单元。该 2.25 小时单元包括 Atlas Search 概述以及如何创建 Atlas Search $search 索引、使用不同操作符的和生成搜索分面的课程。

您还可以观看以下视频,了解关于 Atlas Search 的更多信息:

后退

Atlas Search

在此页面上