Docs 菜单
Docs 主页
/
MongoDB Atlas
/ / /

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

在此页面上

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

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

注意

$lookup 查询的表现欠佳,因为 Atlas Search 会在数据库中对集合中的每个文档进行全文档查找。要了解更多信息,请参阅减少 $lookup 操作。

本教程演示针对 sample_analytics 数据库中的 accountscustomers 集合,如何运行带有 $search$lookup 查询。本教程将引导您完成以下步骤:

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

  2. 使用 $lookup 运行 $search 查询,从 customers 集合中查找帐号同时购买了 accounts 集合中 CurrencyServiceInvestmentStock 产品的客户。

开始之前,请确保 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. 如果尚未出现,请单击侧边栏中的 Clusters(集群)。

    会显示集群页面。

2

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

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

  2. Select data source 下拉菜单中选择您的集群并单击 Go to Atlas Search

    将显示 Atlas Search 页面。

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

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

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

    将显示 Atlas Search 页面。

  1. 单击集群的名称。

  2. 单击 Atlas Search 标签页。

    将显示 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 用户界面中创建索引。

  1. 单击 Next(连接)。

  2. 查看集合的默认索引定义。

  1. 单击 Next(连接)。

  2. 查看索引定义。

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

    {
    "mappings": {
    "dynamic": true
    }
    }
  3. 单击 Next(连接)。

7
8

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

9

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


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


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

1

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

2

mongosh 提示符下运行以下命令:

use sample_analytics
switched to db sample_analytics
3

以下查询使用以下阶段:

  • $lookup 以执行以下操作:

    • 根据客户的账户 ID 连接 sample_analytics 数据库中的 customersaccounts 集合,并在名为 purchases 的数组字段中返回 accounts 集合中的匹配文档。

    • 使用子管道中的 $search 阶段搜索 must 已购买 CurrencyServiceInvestmentStock 的客户帐户,并优先选择介于 500010000 之间的订单限制。

  • $limit 阶段将输出限制为 5 个结果。

  • $project 阶段以排除结果中的指定字段。

db.customers.aggregate([
{
$lookup:{
"from": "accounts",
"localField": "accounts",
"foreignField": "account_id",
"as": "purchases",
"pipeline": [{
"$search": {
"index": "lookup-with-search-tutorial",
"compound": {
"must": [{
"queryString": {
"defaultPath": "products",
"query": "products: (CurrencyService AND InvestmentStock)"
}
}],
"should": [{
"range": {
"path": "limit",
"gte": 5000,
"lte": 10000
}
}]
}
}
},{
"$project": {
"_id": 0
}
}]
}
},{
"$limit": 5
},{
"$project": {
"_id": 0,
"address": 0,
"birthdate": 0,
"username": 0,
"tier_and_details": 0
}
}
])
[
{
name: 'Elizabeth Ray',
email: 'arroyocolton@gmail.com',
active: true,
accounts: [ 371138, 324287, 276528, 332179, 422649, 387979 ],
purchases: [
{
account_id: 422649,
limit: 10000,
products: [ 'CurrencyService', 'InvestmentStock' ]
},
{
account_id: 324287,
limit: 10000,
products: [
'Commodity',
'CurrencyService',
'Derivatives',
'InvestmentStock'
]
},
{
account_id: 332179,
limit: 10000,
products: [
'Commodity',
'CurrencyService',
'InvestmentFund',
'Brokerage',
'InvestmentStock'
]
}
]
},
{
name: 'Lindsay Cowan',
email: 'cooperalexis@hotmail.com',
accounts: [ 116508 ],
purchases: []
},
{
name: 'Katherine David',
email: 'timothy78@hotmail.com',
accounts: [ 462501, 228290, 968786, 515844, 377292 ],
purchases: [
{
account_id: 228290,
limit: 10000,
products: [
'CurrencyService',
'InvestmentStock',
'InvestmentFund',
'Brokerage'
]
},
{
account_id: 515844,
limit: 10000,
products: [
'Commodity',
'CurrencyService',
'InvestmentFund',
'Brokerage',
'InvestmentStock'
]
}
]
},
{
name: 'Leslie Martinez',
email: 'tcrawford@gmail.com',
accounts: [ 170945, 951849 ],
purchases: []
},
{
name: 'Brad Cardenas',
email: 'dustin37@yahoo.com',
accounts: [ 721914, 817222, 973067, 260799, 87389 ],
purchases: [
{
account_id: 87389,
limit: 10000,
products: [ 'CurrencyService', 'InvestmentStock' ]
},
{
account_id: 260799,
limit: 10000,
products: [
'Brokerage',
'InvestmentStock',
'Commodity',
'CurrencyService'
]
}
]
}
]
1

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

2

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

3

以下查询使用以下阶段:

  • $lookup 以执行以下操作:

    • 根据客户的账户 ID 连接 sample_analytics 数据库中的 customersaccounts 集合,并在名为 purchases 的数组字段中返回 accounts 集合中的匹配文档。

    • 使用子管道中的 $search 阶段搜索 must 已购买 CurrencyServiceInvestmentStock 的客户帐户,并优先选择介于 500010000 之间的订单限制。

  • $limit 阶段将输出限制为 5 个结果。

  • $project 阶段以排除结果中的指定字段。

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

  1. 单击 Aggregations 标签页。

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

    管道阶段
    查询

    $lookup

    {
    from: "accounts",
    localField: "accounts",
    foreignField: "account_id",
    as: "purchases",
    pipeline: [
    {
    $search: {
    index: "lookup-with-search-tutorial",
    compound: {
    must: [
    {
    queryString: {
    defaultPath: "products",
    query:
    "products: (CurrencyService AND InvestmentStock)"
    }
    }
    ],
    should: [
    {
    range: {
    path: "limit",
    gte: 5000,
    lte: 10000,
    }
    }
    ]
    }
    }
    },
    {
    $project: {
    _id: 0,
    }
    }
    ]
    }

    $limit

    5

    $project

    {
    _id: 0,
    address: 0,
    birthdate: 0,
    username: 0,
    tier_and_details: 0,
    }

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

    name: Elizabeth Ray
    email: arroyocolton@gmail.com
    active: True
    accounts: Array (6)
    purchases: Array (3)
    name: "Lindsay Cowan"
    email: "cooperalexis@hotmail.com"
    accounts: Array (1)
    purchases: Array (empty)
    name: "Katherine David"
    email: "timothy78@hotmail.com"
    accounts: Array (5)
    urchases: Array (2)
    name: "Leslie Martinez"
    email: "tcrawford@gmail.com"
    accounts: Array (2)
    purchases: Array (empty)
    name: "Brad Cardenas"
    email: "dustin37@yahoo.com"
    accounts: Array (5)
    purchases: Array (2)
4

对于在结果中返回的文档,MongoDB Compass 可能不会显示该文档对象内的所有字段和数组内的所有值。如要查看所有字段和值,请展开结果中的字段。

1
  1. 创建一个名为 lookup-with-search 的新目录,并使用 dotnet new 命令初始化项目。

    mkdir lookup-with-search
    cd lookup-with-search
    dotnet new console
  2. 将 .NET/C# 驱动程序作为依赖项添加到项目中。

    dotnet add package MongoDB.Driver
2

以下查询使用以下阶段:

  • $lookup 以执行以下操作:

    • 根据客户的账户 ID 连接 sample_analytics 数据库中的 customersaccounts 集合,并在名为 purchases 的数组字段中返回 accounts 集合中的匹配文档。

    • 使用子管道中的 $search 阶段搜索 must 已购买 CurrencyServiceInvestmentStock 的客户帐户,并优先选择介于 500010000 之间的订单限制。

  • $limit 阶段将输出限制为 5 个结果。

  • $project 阶段以排除结果中的指定字段。

1using MongoDB.Bson;
2using MongoDB.Bson.Serialization.Attributes;
3using MongoDB.Bson.Serialization.Conventions;
4using MongoDB.Driver;
5using MongoDB.Driver.Core;
6using MongoDB.Driver.Search;
7
8public class LookupWithSearch{
9
10 static void Main(string[] args) {// allow automapping of the camelCase database fields to our MovieDocument
11 var camelCaseConvention = new ConventionPack { new CamelCaseElementNameConvention() };
12 ConventionRegistry.Register("CamelCase", camelCaseConvention, type => true);
13
14 // connect to your Atlas cluster
15 var mongoClient = new MongoClient("<connection-string>");
16
17 // define namespace
18 var analyticsDatabase = mongoClient.GetDatabase("sample_analytics");
19 var accountsCollection = analyticsDatabase.GetCollection<AccountDocument>("accounts");
20 var customersCollection = analyticsDatabase.GetCollection<CustomerDocument>("customers");
21
22 // define pipeline stages
23 var lookupStage = new BsonDocument("$lookup", new BsonDocument{
24 { "from", "accounts" }, { "localField", "accounts" }, { "foreignField", "account_id" },
25 { "as", "purchases" }, { "pipeline", new BsonArray{
26 new BsonDocument("$search", new BsonDocument{
27 { "index", "lookup-with-search-tutorial" }, { "compound", new BsonDocument{
28 { "must", new BsonArray{
29 new BsonDocument("queryString", new BsonDocument{
30 { "defaultPath", "products" }, { "query", "products: (CurrencyService AND InvestmentStock)" }
31 })
32 }},
33 { "should", new BsonArray{
34 new BsonDocument("range", new BsonDocument{
35 { "path", "limit" }, { "gte", 5000 }, { "lte", 10000 }
36 })
37 }}
38 }}
39 })
40 }}
41 });
42 var projectStage1 = new BsonDocument("$project", new BsonDocument("_id", 0));
43 var limitStage = new BsonDocument("$limit", 5);
44 var projectStage2 = new BsonDocument("$project", new BsonDocument{
45 { "_id", 0 }, { "address", 0 }, { "birthdate", 0 }, { "username", 0 }, { "tier_and_details", 0 }
46 });
47 var aggregationPipeline = new List<BsonDocument> {lookupStage, projectStage1, limitStage, projectStage2};
48
49 // run pipeline
50 var results = customersCollection.Aggregate<BsonDocument>(aggregationPipeline).ToList();
51
52 // print results
53 foreach (var acct in results) {
54 Console.WriteLine(acct.ToJson());
55 }
56 }
57}
58
59// define fields in the accounts collection
60[BsonIgnoreExtraElements]
61public class AccountDocument {
62 [BsonId]
63 [BsonRepresentation(BsonType.ObjectId)]
64 [BsonElement("_id")]
65 public string Id { get; set; }
66
67 [BsonElement("account_id")]
68 public int AccountId { get; set; }
69
70 [BsonElement("limit")]
71 public int Limit { get; set; }
72}
73
74// define fields in the customers collection
75[BsonIgnoreExtraElements]
76public class CustomerDocument {
77 [BsonId]
78 [BsonRepresentation(BsonType.ObjectId)]
79 [BsonElement("_id")]
80 public ObjectId Id { get; set; }
81
82 [BsonElement("name")]
83 public string Name { get; set; }
84
85 [BsonElement("email")]
86 public string Email { get; set; }
87
88 [BsonElement("active")]
89 public bool Active { get; set; }
90
91 [BsonElement("accounts")]
92 public List<int> Accounts { get; set; }
93}
94
95// define new array field for matching documents
96public class CustomerLookedUp: CustomerDocument{
97 public List<CustomerDocument> Purchases { get; set; }
98}
3

确保您的连接字符串包含数据库用户的档案。要了解详情,请参阅通过驱动程序连接

4
dotnet run lookup-with-search.csproj
{
"name" : "Elizabeth Ray",
"email" : "arroyocolton@gmail.com",
"active" : true,
"accounts" : [371138, 324287, 276528, 332179, 422649,
387979],
"purchases" : [
{
"_id" : ObjectId("5ca4bbc7a2dd94ee58162402"),
"account_id" : 422649,
"limit" : 10000,
"products" : ["CurrencyService", "InvestmentStock"]
},
{
"_id" : ObjectId("5ca4bbc7a2dd94ee581623a9"),
"account_id" : 324287,
"limit" : 10000,
"products" : ["Commodity", "CurrencyService", "Derivatives", "InvestmentStock"]
},
{
"_id" : ObjectId("5ca4bbc7a2dd94ee58162400"),
"account_id" : 332179,
"limit" : 10000,
"products" : ["Commodity", "CurrencyService", "InvestmentFund", "Brokerage", "InvestmentStock"]
}
]
}
{
"name" : "Lindsay Cowan",
"email" : "cooperalexis@hotmail.com",
"accounts" : [116508],
"purchases" : []
}
{
"name" : "Katherine David",
"email" : "timothy78@hotmail.com",
"accounts" : [462501, 228290, 968786, 515844, 377292],
"purchases" : [
{
"_id" : ObjectId("5ca4bbc7a2dd94ee581623c9"),
"account_id" : 228290,
"limit" : 10000,
"products" : ["CurrencyService", "InvestmentStock", "InvestmentFund", "Brokerage"] },
{
"_id" : ObjectId("5ca4bbc7a2dd94ee581623cb"),
"account_id" : 515844,
"limit" : 10000,
"products" : ["Commodity", "CurrencyService", "InvestmentFund", "Brokerage", "InvestmentStock"]
}
]
}
{
"name" : "Leslie Martinez",
"email" : "tcrawford@gmail.com",
"accounts" : [170945, 951849],
"purchases" : []
}
{
"name" : "Brad Cardenas",
"email" : "dustin37@yahoo.com",
"accounts" : [721914, 817222, 973067, 260799, 87389],
"purchases" : [
{
"_id" : ObjectId("5ca4bbc7a2dd94ee581623d6"),
"account_id" : 87389,
"limit" : 10000,
"products" : ["CurrencyService", "InvestmentStock"] },
{
"_id" : ObjectId("5ca4bbc7a2dd94ee581623d5"),
"account_id" : 260799,
"limit" : 10000,
"products" : ["Brokerage", "InvestmentStock", "Commodity", "CurrencyService"]
}
]
}
1
2

以下查询使用以下阶段:

  • $lookup 以执行以下操作:

    • 根据客户的账户 ID 连接 sample_analytics 数据库中的 customersaccounts 集合,并在名为 purchases 的数组字段中返回 accounts 集合中的匹配文档。

    • 使用子管道中的 $search 阶段搜索 must 已购买 CurrencyServiceInvestmentStock 的客户帐户,并优先选择介于 500010000 之间的订单限制。

  • $limit 阶段将输出限制为 5 个结果。

  • $project 阶段以排除结果中的指定字段。

1package main
2import (
3 "context"
4 "fmt"
5 "time"
6
7 "go.mongodb.org/mongo-driver/bson"
8 "go.mongodb.org/mongo-driver/mongo"
9 "go.mongodb.org/mongo-driver/mongo/options"
10)
11
12func main() {
13 var err error
14 // connect to the Atlas cluster
15 ctx := context.Background()
16 client, err := mongo.Connect(ctx, options.Client().ApplyURI("<connection-string>"))
17 if err != nil {
18 panic(err)
19 }
20 defer client.Disconnect(ctx)
21 // set namespace
22 collection := client.Database("sample_analytics").Collection("customers")
23 // define pipeline
24 lookupStage := bson.D{{"$lookup", bson.D{
25 {"from", "accounts"},
26 {"localField", "accounts"},
27 {"foreignField", "account_id"},
28 {"as", "purchases"},
29 {"pipeline", bson.A{
30 bson.D{
31 {"$search", bson.D{
32 {"index", "lookup-with-search-tutorial"},
33 {"compound", bson.D{
34 {"must", bson.A{
35 bson.D{{"queryString", bson.D{
36 {"defaultPath", "products"},
37 {"query", "products: (CurrencyService AND InvestmentStock)"},
38 }}},
39 }},
40 {"should", bson.A{
41 bson.D{{"range", bson.D{
42 {"path", "limit"},
43 {"gte", 5000},
44 {"lte", 10000},
45 }}},
46 }},
47 }},
48 }},
49 },
50 bson.D{{"$project", bson.D{
51 {"_id", 0},
52 {"address", 0},
53 {"birthdate", 0},
54 {"username", 0},
55 {"tier_and_details", 0},
56 }}},
57 }},
58 }}}
59 limitStage := bson.D{{"$limit", 5}}
60 projectStage := bson.D{{"$project", bson.D{
61 {"name", 1},
62 {"email", 1},
63 {"active", 1},
64 {"accounts", 1},
65 {"purchases", 1},
66 }}}
67 // specify the amount of time the operation can run on the server
68 opts := options.Aggregate().SetMaxTime(5 * time.Second)
69 // run pipeline
70 cursor, err := collection.Aggregate(ctx, mongo.Pipeline{lookupStage, limitStage, projectStage}, opts)
71 if err != nil {
72 panic(err)
73 }
74 // print results
75 var results []bson.D
76 if err = cursor.All(context.TODO(), &results); err != nil {
77 panic(err)
78 }
79 for _, result := range results {
80 fmt.Println(result)
81 }
82}
3

确保您的连接字符串包含数据库用户的档案。要了解详情,请参阅通过驱动程序连接

4
go run lookup-with-search-query.go
[{_id ObjectID("5ca4bbcea2dd94ee58162a68")} {name Elizabeth Ray} {email arroyocolton@gmail.com} {active true} {accounts [371138 324287 276528 332179 422649 387979]} {purchases [[{account_id 422649} {limit 10000} {products [CurrencyService InvestmentStock]}] [{account_id 324287} {limit 10000} {products [Commodity CurrencyService Derivatives InvestmentStock]}] [{account_id 332179} {limit 10000} {products [Commodity CurrencyService InvestmentFund Brokerage InvestmentStock]}]]}]
[{_id ObjectID("5ca4bbcea2dd94ee58162a69")} {name Lindsay Cowan} {email cooperalexis@hotmail.com} {accounts [116508]} {purchases []}]
[{_id ObjectID("5ca4bbcea2dd94ee58162a6a")} {name Katherine David} {email timothy78@hotmail.com} {accounts [462501 228290 968786 515844 377292]} {purchases [[{account_id 228290} {limit 10000} {products [CurrencyService InvestmentStock InvestmentFund Brokerage]}] [{account_id 515844} {limit 10000} {products [Commodity CurrencyService InvestmentFund Brokerage InvestmentStock]}]]}]
[{_id ObjectID("5ca4bbcea2dd94ee58162a6b")} {name Leslie Martinez} {email tcrawford@gmail.com} {accounts [170945 951849]} {purchases []}]
[{_id ObjectID("5ca4bbcea2dd94ee58162a6c")} {name Brad Cardenas} {email dustin37@yahoo.com} {accounts [721914 817222 973067 260799 87389]} {purchases [[{account_id 87389} {limit 10000} {products [CurrencyService InvestmentStock]}] [{account_id 260799} {limit 10000} {products [Brokerage InvestmentStock Commodity CurrencyService]}]]}]
1

junit

4.11 或更高版本

mongodb-driver-sync

4.3.0 或更高版本

slf4j-log4j12

1.7.30 或更高版本

2
3

以下查询使用以下阶段:

  • $lookup 以执行以下操作:

    • 根据客户的账户 ID 连接 sample_analytics 数据库中的 customersaccounts 集合,并在名为 purchases 的数组字段中返回 accounts 集合中的匹配文档。

    • 使用子管道中的 $search 阶段搜索 must 已购买 CurrencyServiceInvestmentStock 的客户帐户,并优先选择介于 500010000 之间的订单限制。

  • $limit 阶段将输出限制为 5 个结果。

  • $project 阶段以排除结果中的指定字段。

1import static com.mongodb.client.model.Aggregates.limit;
2import static com.mongodb.client.model.Aggregates.project;
3import static com.mongodb.client.model.Projections.*;
4import java.util.Arrays;
5import com.mongodb.client.MongoClient;
6import com.mongodb.client.MongoClients;
7import com.mongodb.client.MongoCollection;
8import com.mongodb.client.MongoDatabase;
9import org.bson.Document;
10
11public class LookupWithSearchQuery {
12
13 public static void main(String[] args) {
14 // connect to your Atlas cluster
15 String uri = "<connection-string>";
16
17 try (MongoClient mongoClient = MongoClients.create(uri)) {
18 // set namespace
19 MongoDatabase database = mongoClient.getDatabase("sample_analytics");
20 MongoCollection<Document> collection = database.getCollection("customers");
21
22 // define pipeline
23 Document agg = new Document("$lookup",
24 new Document("from", "accounts")
25 .append("localField", "accounts")
26 .append("foreignField", "account_id")
27 .append("as", "purchases")
28 .append("pipeline", Arrays.asList(new Document("$search",
29 new Document("index", "lookup-with-search-tutorial")
30 .append("compound",
31 new Document("must", Arrays.asList(new Document("queryString",
32 new Document("defaultPath", "products")
33 .append("query", "products: (CurrencyService AND InvestmentStock)"))))
34 .append("should", Arrays.asList(new Document("range",
35 new Document("path", "limit")
36 .append("gte", 5000L)
37 .append("lte", 10000L)
38 )))
39 )
40 ),
41 new Document("$limit", 5L),
42 new Document("$project",
43 new Document("_id", 0L)
44 .append("address", 0L)
45 .append("birthdate", 0L)
46 .append("username", 0L)
47 .append("tier_and_details", 0L)
48 )))
49 );
50 // run pipeline and print results
51 collection.aggregate(Arrays.asList(agg,
52 limit(5),
53 project(fields(excludeId(), include("name", "email", "active", "accounts", "purchases")))
54 ))
55 .forEach(doc -> System.out.println(doc.toJson()));
56 }
57 }
58}

注意

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

package com.mongodb.drivers;
4

确保您的连接字符串包含数据库用户的档案。要了解详情,请参阅通过驱动程序连接

5
javac LookupWithSearchQuery.java
java LookupWithSearchQuery
{"name": "Elizabeth Ray", "email": "arroyocolton@gmail.com", "active": true, "accounts": [371138, 324287, 276528, 332179, 422649, 387979], "purchases": [{"account_id": 422649, "limit": 10000, "products": ["CurrencyService", "InvestmentStock"]}, {"account_id": 324287, "limit": 10000, "products": ["Commodity", "CurrencyService", "Derivatives", "InvestmentStock"]}, {"account_id": 332179, "limit": 10000, "products": ["Commodity", "CurrencyService", "InvestmentFund", "Brokerage", "InvestmentStock"]}]}
{"name": "Lindsay Cowan", "email": "cooperalexis@hotmail.com", "accounts": [116508], "purchases": []}
{"name": "Katherine David", "email": "timothy78@hotmail.com", "accounts": [462501, 228290, 968786, 515844, 377292], "purchases": [{"account_id": 228290, "limit": 10000, "products": ["CurrencyService", "InvestmentStock", "InvestmentFund", "Brokerage"]}, {"account_id": 515844, "limit": 10000, "products": ["Commodity", "CurrencyService", "InvestmentFund", "Brokerage", "InvestmentStock"]}]}
{"name": "Leslie Martinez", "email": "tcrawford@gmail.com", "accounts": [170945, 951849], "purchases": []}
{"name": "Brad Cardenas", "email": "dustin37@yahoo.com", "accounts": [721914, 817222, 973067, 260799, 87389], "purchases": [{"account_id": 87389, "limit": 10000, "products": ["CurrencyService", "InvestmentStock"]}, {"account_id": 260799, "limit": 10000, "products": ["Brokerage", "InvestmentStock", "Commodity", "CurrencyService"]}]}
1

mongodb-driver-kotlin-coroutine

4.10.0 或更高版本

2
3

以下查询使用以下阶段:

  • $lookup 以执行以下操作:

    • 根据客户的账户 ID 连接 sample_analytics 数据库中的 customersaccounts 集合,并在名为 purchases 的数组字段中返回 accounts 集合中的匹配文档。

    • 使用子管道中的 $search 阶段搜索 must 已购买 CurrencyServiceInvestmentStock 的客户帐户,并优先选择介于 500010000 之间的订单限制。

  • $limit 阶段将输出限制为 5 个结果。

  • $project 阶段以排除结果中的指定字段。

1import com.mongodb.client.model.Aggregates.limit
2import com.mongodb.client.model.Aggregates.project
3import com.mongodb.client.model.Projections.*
4import com.mongodb.kotlin.client.coroutine.MongoClient
5import kotlinx.coroutines.runBlocking
6import org.bson.Document
7import java.util.*
8
9fun main() {
10 // connect to your Atlas cluster
11 val uri = "<connection-string>"
12 val mongoClient = MongoClient.create(uri)
13
14 // set namespace
15 val database = mongoClient.getDatabase("sample_analytics")
16 val collection = database.getCollection<Document>("customers")
17
18 runBlocking {
19 // define pipeline
20 val agg = Document(
21 "\$lookup",
22 Document("from", "accounts")
23 .append("localField", "accounts")
24 .append("foreignField", "account_id")
25 .append("as", "purchases")
26 .append(
27 "pipeline", Arrays.asList(
28 Document(
29 "\$search",
30 Document("index", "lookup-with-search-tutorial")
31 .append(
32 "compound",
33 Document(
34 "must", Arrays.asList(
35 Document(
36 "queryString",
37 Document("defaultPath", "products")
38 .append("query", "products: (CurrencyService AND InvestmentStock)")
39 )
40 )
41 )
42 .append(
43 "should", Arrays.asList(
44 Document(
45 "range",
46 Document("path", "limit")
47 .append("gte", 5000)
48 .append("lte", 10000)
49 )
50 )
51 )
52 )
53 ),
54 Document("\$limit", 5),
55 Document(
56 "\$project",
57 Document("_id", 0)
58 .append("address", 0)
59 .append("birthdate", 0)
60 .append("username", 0)
61 .append("tier_and_details", 0)
62 )
63 )
64 )
65 )
66
67 // run pipeline and print results
68 val resultsFlow = collection.aggregate<Document>(
69 listOf(
70 agg,
71 limit(5),
72 project(fields(excludeId(), include("name", "email", "active", "accounts", "purchases")))
73 )
74 )
75 resultsFlow.collect { println(it) }
76 }
77 mongoClient.close()
78}
4

确保您的连接字符串包含数据库用户的档案。要了解详情,请参阅通过驱动程序连接

5

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

Document{{name=Elizabeth Ray, email=arroyocolton@gmail.com, active=true, accounts=[371138, 324287, 276528, 332179, 422649, 387979], purchases=[Document{{account_id=422649, limit=10000, products=[CurrencyService, InvestmentStock]}}, Document{{account_id=324287, limit=10000, products=[Commodity, CurrencyService, Derivatives, InvestmentStock]}}, Document{{account_id=332179, limit=10000, products=[Commodity, CurrencyService, InvestmentFund, Brokerage, InvestmentStock]}}]}}
Document{{name=Lindsay Cowan, email=cooperalexis@hotmail.com, accounts=[116508], purchases=[]}}
Document{{name=Katherine David, email=timothy78@hotmail.com, accounts=[462501, 228290, 968786, 515844, 377292], purchases=[Document{{account_id=228290, limit=10000, products=[CurrencyService, InvestmentStock, InvestmentFund, Brokerage]}}, Document{{account_id=515844, limit=10000, products=[Commodity, CurrencyService, InvestmentFund, Brokerage, InvestmentStock]}}]}}
Document{{name=Leslie Martinez, email=tcrawford@gmail.com, accounts=[170945, 951849], purchases=[]}}
Document{{name=Brad Cardenas, email=dustin37@yahoo.com, accounts=[721914, 817222, 973067, 260799, 87389], purchases=[Document{{account_id=87389, limit=10000, products=[CurrencyService, InvestmentStock]}}, Document{{account_id=260799, limit=10000, products=[Brokerage, InvestmentStock, Commodity, CurrencyService]}}]}}
1
2

以下查询使用以下阶段:

  • $lookup 以执行以下操作:

    • 根据客户的账户 ID 连接 sample_analytics 数据库中的 customersaccounts 集合,并在名为 purchases 的数组字段中返回 accounts 集合中的匹配文档。

    • 使用子管道中的 $search 阶段搜索 must 已购买 CurrencyServiceInvestmentStock 的客户帐户,并优先选择介于 500010000 之间的订单限制。

  • $limit 阶段将输出限制为 5 个结果。

  • $project 阶段以排除结果中的指定字段。

1const MongoClient = require("mongodb").MongoClient;
2const assert = require("assert");
3
4const agg = [
5 {
6 '$lookup': {
7 'from': 'accounts',
8 'localField': 'accounts',
9 'foreignField': 'account_id',
10 'as': 'purchases',
11 'pipeline': [
12 {
13 '$search': {
14 'index': 'lookup-with-search-tutorial',
15 'compound': {
16 'must': [
17 {
18 'queryString': {
19 'defaultPath': 'products',
20 'query': 'products: (CurrencyService AND InvestmentStock)'
21 }
22 }
23 ],
24 'should': [
25 {
26 'range': {
27 'path': 'limit',
28 'gte': 5000,
29 'lte': 10000
30 }
31 }
32 ]
33 }
34 }
35 }, {
36 '$project': {
37 '_id': 0
38 }
39 }
40 ]
41 }
42 }, {
43 '$limit': 5
44 }, {
45 '$project': {
46 '_id': 0,
47 'address': 0,
48 'birthdate': 0,
49 'username': 0,
50 'tier_and_details': 0
51 }
52 }
53 ];
54
55MongoClient.connect(
56 "<connection-string>",
57 { useNewUrlParser: true, useUnifiedTopology: true },
58 async function (connectErr, client) {
59 assert.equal(null, connectErr);
60 const coll = client.db("sample_analytics").collection("customers");
61 let cursor = await coll.aggregate(agg);
62 await cursor.forEach((doc) => console.log(doc));
63 client.close();
64 }
65);
3

确保您的连接字符串包含数据库用户的档案。要了解详情,请参阅通过驱动程序连接

4

运行以下命令来查询您的集合:

node lookup-with-search-query.js
{
name: 'Elizabeth Ray',
email: 'arroyocolton@gmail.com',
active: true,
accounts: [ 371138, 324287, 276528, 332179, 422649, 387979 ],
purchases: [
{ account_id: 422649, limit: 10000, products: [Array] },
{ account_id: 324287, limit: 10000, products: [Array] },
{ account_id: 332179, limit: 10000, products: [Array] }
]
}
{
name: 'Lindsay Cowan',
email: 'cooperalexis@hotmail.com',
accounts: [ 116508 ],
purchases: []
}
{
name: 'Katherine David',
email: 'timothy78@hotmail.com',
accounts: [ 462501, 228290, 968786, 515844, 377292 ],
purchases: [
{ account_id: 228290, limit: 10000, products: [Array] },
{ account_id: 515844, limit: 10000, products: [Array] }
]
}
{
name: 'Leslie Martinez',
email: 'tcrawford@gmail.com',
accounts: [ 170945, 951849 ],
purchases: []
}
{
name: 'Brad Cardenas',
email: 'dustin37@yahoo.com',
accounts: [ 721914, 817222, 973067, 260799, 87389 ],
purchases: [
{ account_id: 87389, limit: 10000, products: [Array] },
{ account_id: 260799, limit: 10000, products: [Array] }
]
}
1
2

以下查询使用以下阶段:

  • $lookup 以执行以下操作:

    • 根据客户的账户 ID 连接 sample_analytics 数据库中的 customersaccounts 集合,并在名为 purchases 的数组字段中返回 accounts 集合中的匹配文档。

    • 使用子管道中的 $search 阶段搜索 must 已购买 CurrencyServiceInvestmentStock 的客户帐户,并优先选择介于 500010000 之间的订单限制。

  • $limit 阶段将输出限制为 5 个结果。

  • $project 阶段以排除结果中的指定字段。

1import datetime
2import pymongo
3
4# connect to your Atlas cluster
5client = pymongo.MongoClient('<connection-string>')
6
7# define pipeline
8pipeline = [
9 {
10 '$lookup': {
11 'from': 'accounts',
12 'localField': 'accounts',
13 'foreignField': 'account_id',
14 'as': 'purchases',
15 'pipeline': [
16 {
17 '$search': {
18 'index': 'lookup-with-search-tutorial',
19 'compound': {
20 'must': [
21 {
22 'queryString': {
23 'defaultPath': 'products',
24 'query': 'products: (CurrencyService AND InvestmentStock)'
25 }
26 }
27 ],
28 'should': [
29 {
30 'range': {
31 'path': 'limit',
32 'gte': 5000,
33 'lte': 10000
34 }
35 }
36 ]
37 }
38 }
39 },
40 { '$project': { '_id': 0 } }
41 ]
42 }
43 },
44 { '$limit': 5 },
45 {
46 '$project': {
47 '_id': 0,
48 'address': 0,
49 'birthdate': 0,
50 'username': 0,
51 'tier_and_details': 0
52 }
53 }
54]
55
56# run pipeline
57result = client['sample_analytics']['customers'].aggregate(pipeline)
58
59# print results
60for i in result:
61 print(i)
3

确保您的连接字符串包含数据库用户的档案。要了解详情,请参阅通过驱动程序连接

4
python lookup-with-search-query.py
{'name': 'Elizabeth Ray', 'email': 'arroyocolton@gmail.com', 'active': True, 'accounts': [371138, 324287, 276528, 332179, 422649, 387979], 'purchases': [{'account_id': 422649, 'limit': 10000, 'products': ['CurrencyService', 'InvestmentStock']}, {'account_id': 324287, 'limit': 10000, 'products': ['Commodity', 'CurrencyService', 'Derivatives', 'InvestmentStock']}, {'account_id': 332179, 'limit': 10000, 'products': ['Commodity', 'CurrencyService', 'InvestmentFund', 'Brokerage', 'InvestmentStock']}]}
{'name': 'Lindsay Cowan', 'email': 'cooperalexis@hotmail.com', 'accounts': [116508], 'purchases': []}
{'name': 'Katherine David', 'email': 'timothy78@hotmail.com', 'accounts': [462501, 228290, 968786, 515844, 377292], 'purchases': [{'account_id': 228290, 'limit': 10000, 'products': ['CurrencyService', 'InvestmentStock', 'InvestmentFund', 'Brokerage']}, {'account_id': 515844, 'limit': 10000, 'products': ['Commodity', 'CurrencyService', 'InvestmentFund', 'Brokerage', 'InvestmentStock']}]}
{'name': 'Leslie Martinez', 'email': 'tcrawford@gmail.com', 'accounts': [170945, 951849], 'purchases': []}
{'name': 'Brad Cardenas', 'email': 'dustin37@yahoo.com', 'accounts': [721914, 817222, 973067, 260799, 87389], 'purchases': [{'account_id': 87389, 'limit': 10000, 'products': ['CurrencyService', 'InvestmentStock']}, {'account_id': 260799, 'limit': 10000, 'products': ['Brokerage', 'InvestmentStock', 'Commodity', 'CurrencyService']}]}

后退

物化视图