如何使用 Atlas Search $search
查询运行 $lookup
从 v6.0 开始,MongoDB$lookup
聚合阶段在 $lookup
pipeline
选项中支持$search
。使用$lookup
,您可以在查询时连接同一数据库中的多个集合,并运行 $search
查询进一步缩小搜索范围。
注意
$lookup
查询的表现欠佳,因为 Atlas Search 会在数据库中对集合中的每个文档进行全文档查找。要了解更多信息,请参阅减少 $lookup
操作。
本教程演示针对 sample_analytics
数据库中的 accounts
和 customers
集合,如何运行带有 $search
的 $lookup
查询。本教程将引导您完成以下步骤:
针对
sample_analytics
数据库中的accounts
集合设置具有动态映射的 Atlas Search 索引。使用
$lookup
运行$search
查询,从customers
集合中查找帐号同时购买了accounts
集合中CurrencyService
和InvestmentStock
产品的客户。
开始之前,请确保 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
或更高的项目访问权限。
创建 Atlas Search 索引
在 sample_analytics.accounts
集合中的所有字段上创建名为 lookup-with-search-tutorial
的 Atlas Search 索引。
AtlasGoClusters在Atlas中,Go项目的 页面。
如果尚未显示,请从导航栏上的 Organizations 菜单中选择包含所需项目的组织。
如果尚未显示,请从导航栏的Projects菜单中选择所需的项目。
如果尚未出现,请单击侧边栏中的 Clusters(集群)。
会显示集群页面。
输入 Index Name(索引名称),然后设置 Database and Collection(数据库和集合)。
在 Index Name 字段中输入
lookup-with-search-tutorial
。如果将索引命名为
default
,则在使用 $search 管道阶段时无需指定index
参数。如果您为索引指定了自定义名称,则必须在index
参数中指定此名称。在 Database and Collection(数据库和集合)部分中找到
sample_analytics
数据库,然后选择accounts
集合。
指定索引定义。
以下索引定义对集合中的支持类型字段动态创建索引。您可以使用 Atlas Search Visual Editor 或 Atlas Search JSON Editor 在 Atlas 用户界面中创建索引。
单击 Next(连接)。
查看集合的默认索引定义。
单击 Next(连接)。
查看索引定义。
索引定义应类似于以下内容:
{ "mappings": { "dynamic": true } } 单击 Next(连接)。
运行带有 $search
的 $lookup
以搜索集合
➤ 使用本页的“选择语言”下拉菜单设置本节示例的语言。
连接到您的 Atlas 集群,针对 sample_analytics
数据库中的索引集合运行样本查询。
通过 mongosh
连接到您的集群。
在终端窗口中打开mongosh
并连接到集群。 有关连接的详细说明,请参阅通过mongosh
连接。
切换到 sample_analytics
数据库。
在 mongosh
提示符下运行以下命令:
use sample_analytics
switched to db sample_analytics
使用 Atlas Search $search
查询运行以下 $lookup
。
以下查询使用以下阶段:
$lookup
以执行以下操作:根据客户的账户 ID 连接
sample_analytics
数据库中的customers
和accounts
集合,并在名为purchases
的数组字段中返回accounts
集合中的匹配文档。使用子管道中的
$search
阶段搜索must
已购买CurrencyService
和InvestmentStock
的客户帐户,并优先选择介于5000
和10000
之间的订单限制。
$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' ] } ] } ]
在 MongoDB Compass 中连接到您的集群。
打开 MongoDB Compass 并连接到您的集群。有关连接的详细说明,请参阅通过 Compass 连接。
对集合运行 Atlas Search 查询。
以下查询使用以下阶段:
$lookup
以执行以下操作:根据客户的账户 ID 连接
sample_analytics
数据库中的customers
和accounts
集合,并在名为purchases
的数组字段中返回accounts
集合中的匹配文档。使用子管道中的
$search
阶段搜索must
已购买CurrencyService
和InvestmentStock
的客户帐户,并优先选择介于5000
和10000
之间的订单限制。
$limit
阶段将输出限制为5
个结果。$project
阶段以排除结果中的指定字段。
若要在 MongoDB Compass 中运行此查询:
单击 Aggregations 标签页。
单击 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)
将查询复制并粘贴到 Program.cs
文件中。
以下查询使用以下阶段:
$lookup
以执行以下操作:根据客户的账户 ID 连接
sample_analytics
数据库中的customers
和accounts
集合,并在名为purchases
的数组字段中返回accounts
集合中的匹配文档。使用子管道中的
$search
阶段搜索must
已购买CurrencyService
和InvestmentStock
的客户帐户,并优先选择介于5000
和10000
之间的订单限制。
$limit
阶段将输出限制为5
个结果。$project
阶段以排除结果中的指定字段。
1 using MongoDB.Bson; 2 using MongoDB.Bson.Serialization.Attributes; 3 using MongoDB.Bson.Serialization.Conventions; 4 using MongoDB.Driver; 5 using MongoDB.Driver.Core; 6 using MongoDB.Driver.Search; 7 8 public 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 [ ]61 public class AccountDocument { 62 [ ]63 [ ]64 [ ]65 public string Id { get; set; } 66 67 [ ]68 public int AccountId { get; set; } 69 70 [ ]71 public int Limit { get; set; } 72 } 73 74 // define fields in the customers collection 75 [ ]76 public class CustomerDocument { 77 [ ]78 [ ]79 [ ]80 public ObjectId Id { get; set; } 81 82 [ ]83 public string Name { get; set; } 84 85 [ ]86 public string Email { get; set; } 87 88 [ ]89 public bool Active { get; set; } 90 91 [ ]92 public List<int> Accounts { get; set; } 93 } 94 95 // define new array field for matching documents 96 public class CustomerLookedUp: CustomerDocument{ 97 public List<CustomerDocument> Purchases { get; set; } 98 }
替换查询中的 <connection-string>
,然后保存该文件。
确保您的连接字符串包含数据库用户的档案。要了解详情,请参阅通过驱动程序连接。
编译并运行 Program.cs
文件。
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"] } ] }
将查询复制并粘贴到 lookup-with-search-query.go
文件中。
以下查询使用以下阶段:
$lookup
以执行以下操作:根据客户的账户 ID 连接
sample_analytics
数据库中的customers
和accounts
集合,并在名为purchases
的数组字段中返回accounts
集合中的匹配文档。使用子管道中的
$search
阶段搜索must
已购买CurrencyService
和InvestmentStock
的客户帐户,并优先选择介于5000
和10000
之间的订单限制。
$limit
阶段将输出限制为5
个结果。$project
阶段以排除结果中的指定字段。
1 package main 2 import ( 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 12 func 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 }
替换查询中的 <connection-string>
,然后保存该文件。
确保您的连接字符串包含数据库用户的档案。要了解详情,请参阅通过驱动程序连接。
运行命令以查询您的集合。
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]}]]}]
将查询复制并粘贴到 LookupWithSearchQuery.java
文件中。
以下查询使用以下阶段:
$lookup
以执行以下操作:根据客户的账户 ID 连接
sample_analytics
数据库中的customers
和accounts
集合,并在名为purchases
的数组字段中返回accounts
集合中的匹配文档。使用子管道中的
$search
阶段搜索must
已购买CurrencyService
和InvestmentStock
的客户帐户,并优先选择介于5000
和10000
之间的订单限制。
$limit
阶段将输出限制为5
个结果。$project
阶段以排除结果中的指定字段。
1 import static com.mongodb.client.model.Aggregates.limit; 2 import static com.mongodb.client.model.Aggregates.project; 3 import static com.mongodb.client.model.Projections.*; 4 import java.util.Arrays; 5 import com.mongodb.client.MongoClient; 6 import com.mongodb.client.MongoClients; 7 import com.mongodb.client.MongoCollection; 8 import com.mongodb.client.MongoDatabase; 9 import org.bson.Document; 10 11 public 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;
替换查询中的 <connection-string>
,然后保存该文件。
确保您的连接字符串包含数据库用户的档案。要了解详情,请参阅通过驱动程序连接。
编译并运行 LookupWithSearchQuery.java
文件。
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"]}]}
将查询复制并粘贴到 LookupWithSearchQuery.kt
文件中。
以下查询使用以下阶段:
$lookup
以执行以下操作:根据客户的账户 ID 连接
sample_analytics
数据库中的customers
和accounts
集合,并在名为purchases
的数组字段中返回accounts
集合中的匹配文档。使用子管道中的
$search
阶段搜索must
已购买CurrencyService
和InvestmentStock
的客户帐户,并优先选择介于5000
和10000
之间的订单限制。
$limit
阶段将输出限制为5
个结果。$project
阶段以排除结果中的指定字段。
1 import com.mongodb.client.model.Aggregates.limit 2 import com.mongodb.client.model.Aggregates.project 3 import com.mongodb.client.model.Projections.* 4 import com.mongodb.kotlin.client.coroutine.MongoClient 5 import kotlinx.coroutines.runBlocking 6 import org.bson.Document 7 import java.util.* 8 9 fun 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 }
替换查询中的 <connection-string>
,然后保存该文件。
确保您的连接字符串包含数据库用户的档案。要了解详情,请参阅通过驱动程序连接。
运行 LookupWithSearchQuery.kt
文件。
当你在 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]}}]}}
将示例查询复制并粘贴到 lookup-with-search-query.js
文件中。
以下查询使用以下阶段:
$lookup
以执行以下操作:根据客户的账户 ID 连接
sample_analytics
数据库中的customers
和accounts
集合,并在名为purchases
的数组字段中返回accounts
集合中的匹配文档。使用子管道中的
$search
阶段搜索must
已购买CurrencyService
和InvestmentStock
的客户帐户,并优先选择介于5000
和10000
之间的订单限制。
$limit
阶段将输出限制为5
个结果。$project
阶段以排除结果中的指定字段。
1 const MongoClient = require("mongodb").MongoClient; 2 const assert = require("assert"); 3 4 const 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 55 MongoClient.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 );
替换查询中的 <connection-string>
,然后保存该文件。
确保您的连接字符串包含数据库用户的档案。要了解详情,请参阅通过驱动程序连接。
查询您的集合。
运行以下命令来查询您的集合:
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] } ] }
将查询复制并粘贴到 lookup-with-search-query.py
文件中。
以下查询使用以下阶段:
$lookup
以执行以下操作:根据客户的账户 ID 连接
sample_analytics
数据库中的customers
和accounts
集合,并在名为purchases
的数组字段中返回accounts
集合中的匹配文档。使用子管道中的
$search
阶段搜索must
已购买CurrencyService
和InvestmentStock
的客户帐户,并优先选择介于5000
和10000
之间的订单限制。
$limit
阶段将输出限制为5
个结果。$project
阶段以排除结果中的指定字段。
1 import pymongo 2 3 # connect to your Atlas cluster 4 client = pymongo.MongoClient('<connection-string>') 5 6 # define pipeline 7 pipeline = [ 8 { 9 '$lookup': { 10 'from': 'accounts', 11 'localField': 'accounts', 12 'foreignField': 'account_id', 13 'as': 'purchases', 14 'pipeline': [ 15 { 16 '$search': { 17 'index': 'lookup-with-search-tutorial', 18 'compound': { 19 'must': [ 20 { 21 'queryString': { 22 'defaultPath': 'products', 23 'query': 'products: (CurrencyService AND InvestmentStock)' 24 } 25 } 26 ], 27 'should': [ 28 { 29 'range': { 30 'path': 'limit', 31 'gte': 5000, 32 'lte': 10000 33 } 34 } 35 ] 36 } 37 } 38 }, 39 { '$project': { '_id': 0 } } 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 55 # run pipeline 56 result = client['sample_analytics']['customers'].aggregate(pipeline) 57 58 # print results 59 for i in result: 60 print(i)
替换查询中的 <connection-string>
,然后保存该文件。
确保您的连接字符串包含数据库用户的档案。要了解详情,请参阅通过驱动程序连接。
运行命令以查询您的集合。
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']}]}