Docs 菜单

Docs 主页启动和管理 MongoDBMongoDB Atlas

$lookup如何使用 Atlas Search$search 查询 运行

在此页面上

  • 创建 Atlas Search 索引
  • 运行带有 $search$lookup 以搜索集合

从 v 开始。6 0,MongoDB$lookup 聚合阶段支持$search $lookuppipeline选项内的 { 。使用$lookup ,您可以在查询时联接同一数据库中的多个集合,并运行$search 查询以进一步缩小搜索范围。

注意

$lookup查询的性能不是很高,因为 Atlas Search 会对数据库中的集合中的每个文档进行完整文档查找。要了解更多信息,请参阅减少$lookup操作。

本教程演示如何使用$lookup $searchaccountscustomers针对sample_analytics 数据库中的 和 集合运行 查询。它将引导您完成以下步骤:

  1. 针对 sample_analytics 数据库中的 accounts 集合设置具有动态映射的 Atlas Search 索引。

  2. $lookup使用$search 运行 查询,以查找customers CurrencyService集合中其帐户同时购买了InvestmentStock accounts集合中的 和 产品的客户。

开始之前,请确保 Atlas 集群满足先决条件中所述的要求。

注意

要使用$lookup 运行 查询,您的集群必须运行 MongoDB$search v6 。0 或更高版本。否则,Atlas Search 会显示以下错误消息:

$_internalSearchMongotRemote is not allowed within a $lookup's sub-pipeline.

要了解更多信息,请参阅升级集群的 MongoDB 主版本

要创建 Atlas Search 索引,您必须拥有 Project Data Access Admin 或更高的项目访问权限。

sample_analytics.accounts 集合中的所有字段上创建名为 lookup-with-search-tutorial 的 Atlas Search 索引。

1
  1. 如果尚未显示,请从导航栏的 Organizations 菜单中选择包含所需项目的组织。

  2. 如果尚未显示该页,请从导航栏的 Projects(项目)菜单中选择所需的项目。

  3. 如果 Database Deployments(数据库部署)页面尚未出现,请单击侧边栏中的 Database(数据库)。

2
  1. 单击集群的名称。

  2. 单击 Atlas Search 标签页。

3

单击 Create Search Index(连接)。

4
  • 要获得引导式体验,请选择 Atlas Search Visual Editor

  • 要编辑原始索引定义,请选择 Atlas SearchJSON Editor

5
  1. Index Name 字段中输入 lookup-with-search-tutorial

    注意

    如果将索引命名为 default,则在使用 $search 管道阶段时,您无需指定 index 参数。否则,您必须使用 index 参数指定索引名称。

  2. Database and Collection(数据库和集合)部分中找到 sample_analytics 数据库,然后选择 accounts 集合。

6

以下索引定义对集合中的支持类型字段动态创建索引。您可以使用 Atlas Search Visual Editor 或 Atlas Search JSON Editor 在 Atlas 用户界面中创建索引。

7
8

此时将显示一个模态窗口,让您知道索引正在构建中。单击 Close 按钮。

9

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


➤ 使用本页的“选择语言”下拉菜单设置本节示例的语言。


连接到您的 Atlas 集群,针对 sample_analytics 数据库中的索引集合运行样本查询。

← 如何使用物化视图运行 Atlas Search 查询