第 2 步:运行 Atlas Search 查询
➤ 使用 Select your language(选择您的语言)下拉菜单设置此页面上示例的语言。
本部分教程将指导您运行 Atlas Search 查询。
步骤
AtlasGoClusters在Atlas中,Go项目的 页面。
如果尚未显示,请从导航栏上的 Organizations 菜单中选择包含所需项目的组织。
如果尚未显示,请从导航栏的Projects菜单中选择所需的项目。
如果尚未出现,请单击侧边栏中的 Clusters(集群)。
显示 集群页面。
转到集群的 Atlas Search 页面。
您可以从侧边栏、 Data Explorer 或集群详细信息页面转到 Atlas Search 页面。
在侧边栏中,单击 Services 标题下的 Atlas Search。
从 Select data source 下拉菜单中选择您的集群并单击 Go to Atlas Search。
将显示 Atlas Search 页面。
单击集群的对应 Browse Collections 按钮。
展开数据库并选择集合。
单击该集合的 Search Indexes 标签页。
将显示 Atlas Search 页面。
单击集群的名称。
单击 Atlas Search 标签页。
将显示 Atlas Search 页面。
对 movies
集合运行简单的 Atlas Search 查询。
将以下查询复制并粘贴到 Query Editor 中,然后点击 Query Editor 中的 Search 按钮。
[ { $search: { index: "default", text: { query: "baseball", path: "plot" } } } ]
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 SCORE: 3.489243507385254 _id: "573a1393f29313caabcdca79" plot: "The story of the life and career of the famed baseball player, Lou Geh..." genres: Array runtime: 128 SCORE: 3.489243507385254 _id: "573a1399f29313caabcecef1" plot: "Babe Ruth becomes a baseball legend but is unheroic to those who know ..." genres: Array runtime: 115 SCORE: 3.4249095916748047 _id: "573a1398f29313caabcebccf" plot: "Two disquieted junior baseball players seek revenge on the local yakuz…" genres: Array runtime: 96 SCORE: 3.4249095916748047 _id: "573a13bdf29313caabd5813d" plot: "Dominican baseball star Miguel "Sugar" Santos is recruited to play in …" genres: Array runtime: 114 SCORE: 3.3629050254821777 _id: "573a139af29313caabcefe79" plot: "An all star baseball player becomes the unhealthy focus of a down on h…" genres: Array runtime: 116 SCORE: 3.303105354309082 _id: "573a1399f29313caabced370" plot: "A fading baseball player is traded to a Japanese team and has trouble …" genres: Array runtime: 108 SCORE: 3.303105354309082 _id: "573a13a0f29313caabd05773" fullplot: "The story of Baseball Hall-of-Famer Hank Greenberg is told through arc…" imdb: Object year: 1998
要了解有关 $search 管道阶段的更多信息,请参阅其参考页面。有关聚合管道的完整文档,请参阅 MongoDB 服务器手册。
展开查询结果。
Search Tester 可能不会显示其所返回文档的所有字段。要查看所有字段,包括在查询路径中指定的字段,请展开结果中的文档。
通过 mongosh
连接到您的集群。
在终端窗口中打开mongosh
并连接到集群。 有关连接的详细说明,请参阅通过mongosh
连接。
使用 sample_mflix
数据库。
在 mongosh
提示符下运行以下命令:
use sample_mflix
对 movies
集合运行简单的 Atlas Search 查询。
以下查询在 plot
字段中搜索单词 baseball
。它包括一个 $limit 阶段,用于将输出限制为 5 个结果,以及一个 $project 阶段,用于排除除 title
和 plot
之外的所有字段。
db.movies.aggregate([ { $search: { "text": { "query": "baseball", "path": "plot" } } }, { $limit: 5 }, { $project: { "_id": 0, "title": 1, "plot": 1 } } ])
{ "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" } { "plot" : "The story of the life and career of the famed baseball player, Lou Gehrig.", "title" : "The Pride of the Yankees" } { "plot" : "Babe Ruth becomes a baseball legend but is unheroic to those who know him.", "title" : "The Babe" }
要了解有关 $search 管道阶段的更多信息,请参阅其参考页面。有关聚合管道的完整文档,请参阅 MongoDB 服务器手册。
对 movies
集合运行复杂的 Atlas Search 查询。
$search
有多个操作符,用于构建不同类型的查询。以下查询使用 复合 操作符将多个操作符组合到单个查询中。它具有以下搜索条件:
plot
字段必须包含Hawaii
或Alaska
。plot
字段必须包含四位数字,例如某个年份。genres
字段不得包含Comedy
或Romance
。title
字段不得包含Beach
或Snow
。
db.movies.aggregate([ { $search: { "compound": { "must": [ { "text": { "query": ["Hawaii", "Alaska"], "path": "plot" }, }, { "regex": { "query": "([0-9]{4})", "path": "plot", "allowAnalyzedField": true } } ], "mustNot": [ { "text": { "query": ["Comedy", "Romance"], "path": "genres" } }, { "text": { "query": ["Beach", "Snow"], "path": "title" } } ] } } }, { $project: { "title": 1, "plot": 1, "genres": 1, "_id": 0 } } ])
{ "plot" : "A modern aircraft carrier is thrown back in time to 1941 near Hawaii, just hours before the Japanese attack on Pearl Harbor.", "genres" : [ "Action", "Sci-Fi" ], "title" : "The Final Countdown" } { "plot" : "Follows John McCain's 2008 presidential campaign, from his selection of Alaska Governor Sarah Palin as his running mate to their ultimate defeat in the general election.", "genres" : [ "Biography", "Drama", "History" ], "title" : "Game Change" } { "plot" : "A devastating and heartrending take on grizzly bear activists Timothy Treadwell and Amie Huguenard, who were killed in October of 2003 while living among grizzlies in Alaska.", "genres" : [ "Documentary", "Biography" ], "title" : "Grizzly Man" } { "plot" : "Truman Korovin is a lonely, sharp-witted cab driver in Fairbanks, Alaska, 1980. The usual routine of picking up fares and spending his nights at his favorite bar, the Boatel, is disrupted ...", "genres" : [ "Drama" ], "title" : "Chronic Town" }
在 MongoDB Compass 中连接到您的集群。
打开 MongoDB Compass 并连接到您的集群。有关连接的详细说明,请参阅通过 Compass 连接。
对 movies
集合运行简单的 Atlas Search 查询。
以下查询在 plot
字段中搜索单词 baseball
。它包括一个 $limit 阶段,用于将输出限制为 5 个结果,以及一个 $project 阶段,用于排除除 title
和 plot
之外的所有字段。
要在 MongoDB Compass 中运行这个简单的 Atlas Search 查询,请执行以下操作:
单击 Aggregations 标签页。
单击 Select...,然后从下拉菜单中选择阶段并为该阶段添加查询,以配置以下每个管道阶段。单击 Add Stage 以添加其他阶段。
管道阶段查询$search
{ "text": { "query": "baseball", "path": "plot" } } $limit
5 $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" } { "plot" : "The story of the life and career of the famed baseball player, Lou Gehrig.", "title" : "The Pride of the Yankees" } { "plot" : "Babe Ruth becomes a baseball legend but is unheroic to those who know him.", "title" : "The Babe" }
要了解有关 $search 管道阶段的更多信息,请参阅其参考页面。有关聚合管道的完整文档,请参阅 MongoDB 服务器手册。
对 movies
集合运行复杂的 Atlas Search 查询。
$search
有多个操作符,用于构建不同类型的查询。以下查询使用 复合 操作符将多个操作符组合到单个查询中。它具有以下搜索条件:
plot
字段必须包含Hawaii
或Alaska
。plot
字段必须包含四位数字,例如某个年份。genres
字段不得包含Comedy
或Romance
。title
字段不得包含Beach
或Snow
。
要在 MongoDB Compass 中运行这个复杂的 Atlas Search 查询,请执行以下操作:
单击 Aggregations 标签页。
单击 Select...,然后从下拉菜单中选择阶段并为该阶段添加查询,以配置以下每个管道阶段。单击 Add Stage 以添加其他阶段。
管道阶段查询$search
{ "compound": { "must": [ { "text": { "query": ["Hawaii", "Alaska"], "path": "plot" }, }, { "regex": { "query": "([0-9]{4})", "path": "plot", "allowAnalyzedField": true } } ], "mustNot": [ { "text": { "query": ["Comedy", "Romance"], "path": "genres" } }, { "text": { "query": ["Beach", "Snow"], "path": "title" } } ] } } $project
{ "title": 1, "plot": 1, "genres": 1, "_id": 0 }
如果启用了 Auto Preview,MongoDB Compass 将在 $project
管道阶段旁边显示以下文档:
{ "plot" : "A modern aircraft carrier is thrown back in time to 1941 near Hawaii, just hours before the Japanese attack on Pearl Harbor.", "genres" : [ "Action", "Sci-Fi" ], "title" : "The Final Countdown" } { "plot" : "Follows John McCain's 2008 presidential campaign, from his selection of Alaska Governor Sarah Palin as his running mate to their ultimate defeat in the general election.", "genres" : [ "Biography", "Drama", "History" ], "title" : "Game Change" } { "plot" : "A devastating and heartrending take on grizzly bear activists Timothy Treadwell and Amie Huguenard, who were killed in October of 2003 while living among grizzlies in Alaska.", "genres" : [ "Documentary", "Biography" ], "title" : "Grizzly Man" } { "plot" : "Truman Korovin is a lonely, sharp-witted cab driver in Fairbanks, Alaska, 1980. The usual routine of picking up fares and spending his nights at his favorite bar, the Boatel, is disrupted ...", "genres" : [ "Drama" ], "title" : "Chronic Town" }
对 movies
集合运行简单的 Atlas Search 查询。
创建一个名为
simple-query-example
的新目录,并使用dotnet new
命令初始化项目。mkdir simple-query-example cd simple-query-example dotnet new console 将 .NET/C# 驱动程序作为依赖项添加到项目中。
dotnet add package MongoDB.Driver 将
Program.cs
文件的内容替换为以下代码。此代码示例将执行以下任务:
导入
mongodb
包和依赖项。建立与您的 Atlas 集群的连接。
在
plot
字段中搜索单词baseball
。它包括:遍历游标以打印与查询匹配的文档。
1 using MongoDB.Bson; 2 using MongoDB.Bson.Serialization.Attributes; 3 using MongoDB.Bson.Serialization.Conventions; 4 using MongoDB.Driver; 5 using MongoDB.Driver.Search; 6 7 public class SimpleQuery 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(5) 30 .ToList(); 31 32 // print results 33 foreach (var movie in results) 34 { 35 Console.WriteLine(movie.ToJson()); 36 } 37 } 38 } 39 40 [ ]41 public class MovieDocument 42 { 43 [ ]44 public ObjectId Id { get; set; } 45 public string Plot { get; set; } 46 public string Title { get; set; } 47 } 在运行示例之前,请将
<connection-string>
替换为 Atlas 连接字符串。确保您的连接字符串包含数据库用户的档案。要了解详情,请参阅通过驱动程序连接。编译并运行
Program.cs
文件。dotnet run simple-query-example.csproj { "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" } { "plot" : "The story of the life and career of the famed baseball player, Lou Gehrig.", "title" : "The Pride of the Yankees" } { "plot" : "Babe Ruth becomes a baseball legend but is unheroic to those who know him.", "title" : "The Babe" }
对 movies
集合运行复杂的 Atlas Search 查询。
创建一个名为
complex-query-example
的新目录,并使用 dotnet new 命令初始化项目。mkdir complex-query-example cd complex-query-example dotnet new console 将 .NET/C# 驱动程序作为依赖项添加到项目中。
dotnet add package MongoDB.Driver 将
Program.cs
文件的内容替换为以下代码。$search
有多个操作符,用于构建不同类型的查询。此代码示例使用复合操作符将多个操作符组合到单个查询中。它具有以下搜索条件:plot
字段必须包含Hawaii
或Alaska
。plot
字段必须包含四位数字,例如某个年份。genres
字段不得包含Comedy
或Romance
。title
字段不得包含Beach
或Snow
。
1 using MongoDB.Bson; 2 using MongoDB.Bson.Serialization.Attributes; 3 using MongoDB.Bson.Serialization.Conventions; 4 using MongoDB.Driver; 5 using MongoDB.Driver.Search; 6 7 public class ComplexQuery 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[] terms = { "Hawaii", "Alaska" }; 24 string[] genres = { "Comedy", "Romance" }; 25 string[] titles = { "Beach", "Snow" }; 26 27 // define and run pipeline 28 var results = moviesCollection.Aggregate() 29 .Search(Builders<MovieDocument>.Search.Compound() 30 .Must(Builders<MovieDocument>.Search.Text(movie => movie.Plot, terms)) 31 .Must(Builders<MovieDocument>.Search.Regex(movie => movie.Plot, "([0-9]{4})", true)) 32 .MustNot((Builders<MovieDocument>.Search.Text(movie => movie.Genres, genres))) 33 .MustNot((Builders<MovieDocument>.Search.Text(movie => movie.Title, titles)))) 34 .Project<MovieDocument>(Builders<MovieDocument>.Projection 35 .Include(movie => movie.Genres) 36 .Include(movie => movie.Plot) 37 .Include(movie => movie.Title) 38 .Exclude(movie => movie.Id)) 39 .ToList(); 40 41 // print results 42 foreach (var movie in results) 43 { 44 Console.WriteLine(movie.ToJson()); 45 } 46 } 47 } 48 49 [ ]50 public class MovieDocument 51 { 52 [ ]53 public ObjectId Id { get; set; } 54 public string[] Genres { get; set; } 55 public string Plot { get; set; } 56 public string Title { get; set; } 57 } 在运行示例之前,请将
<connection-string>
替换为 Atlas 连接字符串。确保您的连接字符串包含数据库用户的档案。要了解详情,请参阅通过驱动程序连接。编译并运行
Program.cs
文件。dotnet run complex-query-example.csproj { "genres" : ["Action", "Sci-Fi"], "plot" : "A modern aircraft carrier is thrown back in time to 1941 near Hawaii, just hours before the Japanese attack on Pearl Harbor.", "title" : "The Final Countdown" } { "genres" : ["Biography", "Drama", "History"], "plot" : "Follows John McCain's 2008 presidential campaign, from his selection of Alaska Governor Sarah Palin as his running mate to their ultimate defeat in the general election.", "title" : "Game Change" } { "genres" : ["Documentary", "Biography"], "plot" : "A devastating and heartrending take on grizzly bear activists Timothy Treadwell and Amie Huguenard, who were killed in October of 2003 while living among grizzlies in Alaska.", "title" : "Grizzly Man" } { "genres" : ["Drama"], "plot" : "Truman Korovin is a lonely, sharp-witted cab driver in Fairbanks, Alaska, 1980. The usual routine of picking up fares and spending his nights at his favorite bar, the Boatel, is disrupted ...", "title" : "Chronic Town" }
对 movies
集合运行简单的 Atlas Search 查询。
创建一个名为
simple-query.go
的文件。将代码示例复制并粘贴到
simple-query.go
文件中。此代码示例将执行以下任务:
导入
mongodb
包和依赖项。建立与您的 Atlas 集群的连接。
在
plot
字段中搜索单词baseball
。它包括以下阶段:遍历游标以打印与查询匹配的文档。
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 // define structure of movies collection 12 type MovieCollection struct { 13 title string `bson:"Title,omitempty"` 14 plot string `bson:"Plot,omitempty"` 15 } 16 func main() { 17 var err error 18 // connect to the Atlas cluster 19 ctx := context.Background() 20 client, err := mongo.Connect(ctx, options.Client().ApplyURI("<connection-string>")) 21 if err != nil { 22 panic(err) 23 } 24 defer client.Disconnect(ctx) 25 // set namespace 26 collection := client.Database("sample_mflix").Collection("movies") 27 // define pipeline 28 searchStage := bson.D{{"$search", bson.D{{"text", bson.D{{"path", "plot"},{"query", "baseball"}}}}}} 29 limitStage := bson.D{{"$limit", 5}} 30 projectStage := bson.D{{"$project", bson.D{{"title", 1}, {"plot", 1}, {"_id", 0}}}} 31 // specify the amount of time the operation can run on the server 32 opts := options.Aggregate().SetMaxTime(5 * time.Second) 33 // run pipeline 34 cursor, err := collection.Aggregate(ctx, mongo.Pipeline{searchStage, limitStage, projectStage}, opts) 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 } 在运行示例之前,请将
<connection-string>
替换为 Atlas 连接字符串。确保您的连接字符串包含数据库用户的档案。要了解详情,请参阅通过驱动程序连接。运行以下命令来查询您的集合:
go run simple-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} ] [ {plot The story of the life and career of the famed baseball player, Lou Gehrig.} {title The Pride of the Yankees} ] [ {plot Babe Ruth becomes a baseball legend but is unheroic to those who know him.} {title The Babe} ]
对 movies
集合运行复杂的 Atlas Search 查询。
创建一个名为
complex-query.go
的文件。将代码示例复制并粘贴到
complex-query.go
文件中。$search
有多个操作符,用于构建不同类型的查询。此代码示例使用复合操作符将多个操作符组合到单个查询中。它具有以下搜索条件:plot
字段必须包含Hawaii
或Alaska
。plot
字段必须包含四位数字,例如某个年份。genres
字段不得包含Comedy
或Romance
。title
字段不得包含Beach
或Snow
。
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 // define structure of movies collection 12 type MovieCollection struct { 13 title string `bson:"Title,omitempty"` 14 plot []string `bson:"Plot,omitempty"` 15 } 16 func main() { 17 var err error 18 // connect to the Atlas cluster 19 ctx := context.Background() 20 client, err := mongo.Connect(ctx, options.Client().ApplyURI("<connection-string>")) 21 if err != nil { 22 panic(err) 23 } 24 defer client.Disconnect(ctx) 25 // set namespace 26 collection := client.Database("sample_mflix").Collection("movies") 27 // define pipeline 28 searchStage := bson.D{{"$search", bson.M{ 29 "compound": bson.M{ 30 "must": bson.A{ 31 bson.M{ 32 "text": bson.D{ 33 {"path", "plot"},{"query", []string{"Hawaii", "Alaska"}}, 34 }, 35 }, 36 bson.M{ 37 "regex": bson.M{ 38 "path": "plot","query": "([0-9]{4})","allowAnalyzedField": true, 39 }, 40 }, 41 }, 42 "mustNot": bson.A{ 43 bson.D{ 44 {"text", bson.M{ 45 "path": "genres","query": []string{"Comedy", "Romance"}, 46 }}, 47 {"text", bson.M{ 48 "path": "title","query": []string{"Beach", "Snow"}, 49 }}, 50 }, 51 }, 52 }, 53 }}} 54 projectStage := bson.D{{"$project", bson.D{{"title", 1}, {"plot", 1}, {"genres", 1}, {"_id", 0}}}} 55 // specify the amount of time the operation can run on the server 56 opts := options.Aggregate().SetMaxTime(5 * time.Second) 57 // run pipeline 58 cursor, err := collection.Aggregate(ctx, mongo.Pipeline{searchStage, projectStage}, opts) 59 if err != nil { 60 panic(err) 61 } 62 // print results 63 var results []bson.D 64 if err = cursor.All(context.TODO(), &results); err != nil { 65 panic(err) 66 } 67 for _, result := range results { 68 fmt.Println(result) 69 } 70 } 在运行示例之前,请将
<connection-string>
替换为 Atlas 连接字符串。确保您的连接字符串包含数据库用户的档案。要了解详情,请参阅通过驱动程序连接。运行以下命令来查询您的集合:
go run complex-query.go [ {plot A modern aircraft carrier is thrown back in time to 1941 near Hawaii, just hours before the Japanese attack on Pearl Harbor.} {genres [Action Sci-Fi]} {title The Final Countdown} ] [ {plot Follows John McCain's 2008 presidential campaign, from his selection of Alaska Governor Sarah Palin as his running mate to their ultimate defeat in the general election.} {genres [Biography Drama History]} {title Game Change} ] [ {plot A devastating and heartrending take on grizzly bear activists Timothy Treadwell and Amie Huguenard, who were killed in October of 2003 while living among grizzlies in Alaska.} {genres [Documentary Biography]} {title Grizzly Man} ] [ {plot Truman Korovin is a lonely, sharp-witted cab driver in Fairbanks, Alaska, 1980. The usual routine of picking up fares and spending his nights at his favorite bar, the Boatel, is disrupted ...} {genres [Drama]} {title Chronic Town} ]
对 movies
集合运行简单的 Atlas Search 查询。
创建一个名为
SimpleQuery.java
的文件。将以下代码复制并粘贴到
SimpleQuery.java
文件。此代码示例将执行以下任务:
导入
mongodb
包和依赖项。建立与您的 Atlas 集群的连接。
在
plot
字段中搜索单词baseball
。它包括:遍历游标以打印与查询匹配的文档。
1 import java.util.Arrays; 2 import static com.mongodb.client.model.Filters.eq; 3 import static com.mongodb.client.model.Aggregates.limit; 4 import static com.mongodb.client.model.Aggregates.project; 5 import static com.mongodb.client.model.Projections.excludeId; 6 import static com.mongodb.client.model.Projections.fields; 7 import static com.mongodb.client.model.Projections.include; 8 import com.mongodb.client.MongoClient; 9 import com.mongodb.client.MongoClients; 10 import com.mongodb.client.MongoCollection; 11 import com.mongodb.client.MongoDatabase; 12 import org.bson.Document; 13 14 public class SimpleQuery { 15 public static void main( String[] args ) { 16 Document agg = new Document("query", "baseball").append("path","plot"); 17 18 String uri = "<connection-string>"; 19 20 try (MongoClient mongoClient = MongoClients.create(uri)) { 21 MongoDatabase database = mongoClient.getDatabase("sample_mflix"); 22 MongoCollection<Document> collection = database.getCollection("movies"); 23 24 collection.aggregate(Arrays.asList( 25 eq("$search", eq("text", agg)), 26 limit(5), 27 project(fields(excludeId(), include("title", "plot")))) 28 ).forEach(doc -> System.out.println(doc.toJson())); 29 } 30 } 31 } 在运行示例之前,请将
<connection-string>
替换为 Atlas 连接字符串。确保您的连接字符串包含数据库用户的档案。要了解详情,请参阅通过驱动程序连接。编译并运行
SimpleQuery.java
文件。javac SimpleQuery.java java SimpleQuery { "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" } { "plot": "The story of the life and career of the famed baseball player, Lou Gehrig.", "title": "The Pride of the Yankees" } { "plot": "Babe Ruth becomes a baseball legend but is unheroic to those who know him.", "title": "The Babe" }
对 movies
集合运行复杂的 Atlas Search 查询。
创建一个名为
ComplexQuery.java
的文件。将以下代码复制并粘贴到
ComplexQuery.java
文件。$search
有多个操作符,用于构建不同类型的查询。此代码示例使用复合操作符将多个操作符组合到单个查询中。它具有以下搜索条件:plot
字段必须包含Hawaii
或Alaska
。plot
字段必须包含四位数字,例如某个年份。genres
字段不得包含Comedy
或Romance
。title
字段不得包含Beach
或Snow
。
1 import java.util.Arrays; 2 import static com.mongodb.client.model.Filters.eq; 3 import static com.mongodb.client.model.Aggregates.project; 4 import static com.mongodb.client.model.Projections.excludeId; 5 import static com.mongodb.client.model.Projections.fields; 6 import static com.mongodb.client.model.Projections.include; 7 import com.mongodb.client.MongoClient; 8 import com.mongodb.client.MongoClients; 9 import com.mongodb.client.MongoCollection; 10 import com.mongodb.client.MongoDatabase; 11 import org.bson.Document; 12 13 public class ComplexQuery { 14 public static void main( String[] args ) { 15 Document agg = new Document("must", Arrays.asList( 16 new Document("text", new Document("query", Arrays.asList("Hawaii", "Alaska")).append("path", "plot")), 17 new Document("regex", new Document("query", "([0-9]{4})").append("path", "plot").append("allowAnalyzedField", true)))) 18 .append("mustNot", Arrays.asList( 19 new Document("text", new Document("query", Arrays.asList("Comedy", "Romance")).append("path", "genres")), 20 new Document("text", new Document("query", Arrays.asList("Beach", "Snow")).append("path", "title")))); 21 22 String uri = "<connection-string>"; 23 24 try (MongoClient mongoClient = MongoClients.create(uri)) { 25 MongoDatabase database = mongoClient.getDatabase("sample_mflix"); 26 MongoCollection<Document> collection = database.getCollection("movies"); 27 28 collection.aggregate(Arrays.asList( 29 eq("$search", eq("compound", agg)), 30 project(fields(excludeId(), include("title", "plot", "genres")))) 31 ).forEach(doc -> System.out.println(doc.toJson())); 32 } 33 } 34 } 在运行示例之前,请将
<connection-string>
替换为 Atlas 连接字符串。确保您的连接字符串包含数据库用户的档案。要了解详情,请参阅通过驱动程序连接。编译并运行
ComplexQuery.java
文件。javac ComplexQuery.java java ComplexQuery { "plot": "A modern aircraft carrier is thrown back in time to 1941 near Hawaii, just hours before the Japanese attack on Pearl Harbor.", "genres": ["Action", "Sci-Fi"], "title": "The Final Countdown" } { "plot": "Follows John McCain's 2008 presidential campaign, from his selection of Alaska Governor Sarah Palin as his running mate to their ultimate defeat in the general election.", "genres": ["Biography", "Drama", "History"], "title": "Game Change" } { "plot": "A devastating and heartrending take on grizzly bear activists Timothy Treadwell and Amie Huguenard, who were killed in October of 2003 while living among grizzlies in Alaska.", "genres": ["Documentary", "Biography"], "title": "Grizzly Man" } { "plot": "Truman Korovin is a lonely, sharp-witted cab driver in Fairbanks, Alaska, 1980. The usual routine of picking up fares and spending his nights at his favorite bar, the Boatel, is disrupted ...", "genres": ["Drama"], "title": "Chronic Town" }
对 movies
集合运行简单的 Atlas Search 查询。
创建一个名为
SimpleQuery.kt
的文件。将以下代码复制并粘贴到
SimpleQuery.kt
文件。此代码示例将执行以下任务:
导入
mongodb
包和依赖项。建立与您的 Atlas 集群的连接。
在
plot
字段中搜索单词baseball
。它包括:打印与
AggregateFlow
实例中的查询相匹配的文档。
1 import com.mongodb.client.model.Aggregates.limit 2 import com.mongodb.client.model.Aggregates.project 3 import com.mongodb.client.model.Filters.eq 4 import com.mongodb.client.model.Projections.* 5 import com.mongodb.kotlin.client.coroutine.MongoClient 6 import kotlinx.coroutines.runBlocking 7 import org.bson.Document 8 9 fun 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(5), 25 project(fields(excludeId(), include("title", "plot"))) 26 ) 27 ) 28 resultsFlow.collect { println(it) } 29 } 30 mongoClient.close() 31 } 在运行示例之前,请将
<connection-string>
替换为 Atlas 连接字符串。确保您的连接字符串包含数据库用户的档案。要了解详情,请参阅通过驱动程序连接。运行
SimpleQuery.kt
文件。当你在 IDE 中运行
SimpleQuery.kt
程序时,它会打印以下文档:Document{{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}} Document{{plot=A young boy is bequeathed the ownership of a professional baseball team., title=Little Big League}} Document{{plot=A trained chimpanzee plays third base for a minor-league baseball team., title=Ed}} Document{{plot=Babe Ruth becomes a baseball legend but is unheroic to those who know him., title=The Babe}} Document{{plot=The story of the life and career of the famed baseball player, Lou Gehrig., title=The Pride of the Yankees}}
对 movies
集合运行复杂的 Atlas Search 查询。
创建一个名为
ComplexQuery.kt
的文件。将以下代码复制并粘贴到
ComplexQuery.kt
文件。$search
有多个操作符,用于构建不同类型的查询。此代码示例使用复合操作符将多个操作符组合到单个查询中。它具有以下搜索条件:plot
字段必须包含Hawaii
或Alaska
。plot
字段必须包含四位数字,例如某个年份。genres
字段不得包含Comedy
或Romance
。title
字段不得包含Beach
或Snow
。
1 import com.mongodb.client.model.Aggregates.limit 2 import com.mongodb.client.model.Aggregates.project 3 import com.mongodb.client.model.Filters.eq 4 import com.mongodb.client.model.Projections.* 5 import com.mongodb.kotlin.client.coroutine.MongoClient 6 import kotlinx.coroutines.runBlocking 7 import org.bson.Document 8 9 fun 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( 19 "must", listOf( 20 Document("text", Document("query", listOf("Hawaii", "Alaska")) 21 .append("path", "plot")), 22 Document( 23 "regex", 24 Document("query", "([0-9]{4})") 25 .append("path", "plot") 26 .append("allowAnalyzedField", true) 27 ) 28 ) 29 ) 30 .append( 31 "mustNot", listOf( 32 Document("text", Document("query", listOf("Comedy", "Romance")) 33 .append("path", "genres")), 34 Document("text", Document("query", listOf("Beach", "Snow")) 35 .append("path", "title")) 36 ) 37 ) 38 39 // run query and print results 40 val resultsFlow = collection.aggregate<Document>( 41 listOf( 42 eq("\$search", eq("compound", agg)), 43 project(fields( 44 excludeId(), 45 include("title", "plot", "genres") 46 )) 47 ) 48 ) 49 resultsFlow.collect { println(it) } 50 } 51 mongoClient.close() 52 } 在运行示例之前,请将
<connection-string>
替换为 Atlas 连接字符串。确保您的连接字符串包含数据库用户的档案。要了解详情,请参阅通过驱动程序连接。运行
ComplexQuery.kt
文件。当你在 IDE 中运行
ComplexQuery.kt
程序时,它会打印以下文档:Document{{plot=A modern aircraft carrier is thrown back in time to 1941 near Hawaii, just hours before the Japanese attack on Pearl Harbor., genres=[Action, Sci-Fi], title=The Final Countdown}} Document{{plot=Follows John McCain's 2008 presidential campaign, from his selection of Alaska Governor Sarah Palin as his running mate to their ultimate defeat in the general election., genres=[Biography, Drama, History], title=Game Change}} Document{{plot=A devastating and heartrending take on grizzly bear activists Timothy Treadwell and Amie Huguenard, who were killed in October of 2003 while living among grizzlies in Alaska., genres=[Documentary, Biography], title=Grizzly Man}} Document{{plot=Truman Korovin is a lonely, sharp-witted cab driver in Fairbanks, Alaska, 1980. The usual routine of picking up fares and spending his nights at his favorite bar, the Boatel, is disrupted ..., genres=[Drama], title=Chronic Town}}
对 movies
集合运行简单的 Atlas Search 查询。
创建一个名为
simple-query.js
的文件。将代码示例复制并粘贴到
simple-query.js
文件中。此代码示例将执行以下任务:
导入
mongodb
,即 MongoDB 的 Node.js 驱动程序。创建一个
MongoClient
类实例,以建立与 Atlas 集群的连接。在
plot
字段中搜索单词baseball
。它包括一个 $limit 阶段,用于将输出限制为 5 个结果,以及一个 $project 阶段,用于排除除title
和plot
之外的所有字段。遍历游标以打印与查询匹配的文档。
1 const MongoClient = require("mongodb").MongoClient; 2 const assert = require("assert"); 3 4 const agg = [ 5 { 6 $search: { 7 text: { 8 query: "baseball", 9 path: "plot", 10 }, 11 }, 12 }, 13 { 14 $limit: 5, 15 }, 16 { 17 $project: { 18 _id: 0, 19 title: 1, 20 plot: 1, 21 }, 22 }, 23 ]; 24 25 MongoClient.connect( 26 "<connection-string>", 27 { useNewUrlParser: true, useUnifiedTopology: true }, 28 async function (connectErr, client) { 29 assert.equal(null, connectErr); 30 const coll = client.db("sample_mflix").collection("movies"); 31 let cursor = await coll.aggregate(agg); 32 await cursor.forEach((doc) => console.log(doc)); 33 client.close(); 34 } 35 ); 在运行示例之前,请将
<connection-string>
替换为 Atlas 连接字符串。确保您的连接字符串包含数据库用户的档案。要了解详情,请参阅通过驱动程序连接。运行以下命令来查询您的集合:
node simple-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' } { plot: 'The story of the life and career of the famed baseball player, Lou Gehrig.', title: 'The Pride of the Yankees' } { plot: 'Babe Ruth becomes a baseball legend but is unheroic to those who know him.', title: 'The Babe' }
对 movies
集合运行复杂的 Atlas Search 查询。
创建一个名为
complex-query.js
的文件。将代码示例复制并粘贴到
complex-query.js
文件中。$search
有多个操作符,用于构建不同类型的查询。该代码示例使用复合操作符将多个操作符组合成单个查询。它具有以下搜索条件:plot
字段必须包含Hawaii
或Alaska
。plot
字段必须包含四位数字,例如某个年份。genres
字段不得包含Comedy
或Romance
。title
字段不得包含Beach
或Snow
。
1 const MongoClient = require("mongodb").MongoClient; 2 const assert = require("assert"); 3 4 const agg = [ 5 { 6 $search: { 7 compound: { 8 must: [ 9 { 10 text: { 11 query: ["Hawaii", "Alaska"], 12 path: "plot", 13 }, 14 }, 15 { 16 regex: { 17 query: "([0-9]{4})", 18 path: "plot", 19 allowAnalyzedField: true, 20 }, 21 }, 22 ], 23 mustNot: [ 24 { 25 text: { 26 query: ["Comedy", "Romance"], 27 path: "genres", 28 }, 29 }, 30 { 31 text: { 32 query: ["Beach", "Snow"], 33 path: "title", 34 }, 35 }, 36 ], 37 }, 38 }, 39 }, 40 { 41 $project: { 42 title: 1, 43 plot: 1, 44 genres: 1, 45 _id: 0, 46 }, 47 }, 48 ]; 49 50 MongoClient.connect( 51 "<connection-string>", 52 { useNewUrlParser: true, useUnifiedTopology: true }, 53 async function (connectErr, client) { 54 assert.equal(null, connectErr); 55 const coll = client.db("sample_mflix").collection("movies"); 56 let cursor = await coll.aggregate(agg); 57 await cursor.forEach((doc) => console.log(doc)); 58 client.close(); 59 } 60 ); 在运行示例之前,请将
<connection-string>
替换为 Atlas 连接字符串。确保您的连接字符串包含数据库用户的凭证。运行以下命令来查询您的集合:
node complex-query.js { plot: 'A modern aircraft carrier is thrown back in time to 1941 near Hawaii, just hours before the Japanese attack on Pearl Harbor.', genres: [ 'Action', 'Sci-Fi' ], title: 'The Final Countdown' } { plot: "Follows John McCain's 2008 presidential campaign, from his selection of Alaska Governor Sarah Palin as his running mate to their ultimate defeat in the general election.", genres: [ 'Biography', 'Drama', 'History' ], title: 'Game Change' } { plot: 'A devastating and heartrending take on grizzly bear activists Timothy Treadwell and Amie Huguenard, who were killed in October of 2003 while living among grizzlies in Alaska.', genres: [ 'Documentary', 'Biography' ], title: 'Grizzly Man' } { plot: 'Truman Korovin is a lonely, sharp-witted cab driver in Fairbanks, Alaska, 1980. The usual routine of picking up fares and spending his nights at his favorite bar, the Boatel, is disrupted ...', genres: [ 'Drama' ], title: 'Chronic Town' }
对 movies
集合运行简单的 Atlas Search 查询。
创建一个名为
simple-query.py
的文件。将代码示例复制并粘贴到
simple-query.py
文件中。以下代码示例:
导入
pymongo
、MongoDB 的 Python 驱动程序和dns
模块,这是使用 DNS 种子列表连接字符串将pymongo
连接到Atlas
所必需的。创建一个
MongoClient
类实例,以建立与 Atlas 集群的连接。在
plot
字段中搜索单词baseball
。它包括一个 $limit 阶段,用于将输出限制为 5 个结果,以及一个 $project 阶段,用于排除除title
和plot
之外的所有字段。遍历游标以打印与查询匹配的文档。
1 import pymongo 2 import dns 3 4 client = pymongo.MongoClient('<connection-string>') 5 result = client['sample_mflix']['movies'].aggregate([ 6 { 7 '$search': { 8 'index': 'default', 9 'text': { 10 'query': 'baseball', 11 'path': 'plot' 12 } 13 } 14 }, { 15 '$limit': 5 16 }, { 17 '$project': { 18 '_id': 0, 19 'title': 1, 20 'plot': 1 21 } 22 } 23 ]) 24 25 for i in result: 26 print(i) 在运行示例之前,请将
<connection-string>
替换为 Atlas 连接字符串。确保您的连接字符串包含数据库用户的档案。要了解详情,请参阅通过驱动程序连接。运行以下命令来查询您的集合:
python simple-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'} {'plot': 'The story of the life and career of the famed baseball player, Lou Gehrig.', 'title': 'The Pride of the Yankees'} {'plot': 'Babe Ruth becomes a baseball legend but is unheroic to those who know him.', 'title': 'The Babe'}
对 movies
集合运行复杂的 Atlas Search 查询。
创建一个名为
complex-query.py
的文件。将代码示例复制并粘贴到
complex-query.py
文件中。$search
有多个操作符,用于构建不同类型的查询。以下查询使用 复合 操作符将多个操作符组合到单个查询中。它具有以下搜索条件:plot
字段必须包含Hawaii
或Alaska
。plot
字段必须包含四位数字,例如某个年份。genres
字段不得包含Comedy
或Romance
。title
字段不得包含Beach
或Snow
。
1 import pymongo 2 import dns 3 4 client = pymongo.MongoClient('<connection-string>') 5 result = client['sample_mflix']['movies'].aggregate([ 6 { 7 '$search': { 8 'compound': { 9 'must': [ 10 { 11 'text': { 12 'query': [ 13 'Hawaii', 'Alaska' 14 ], 15 'path': 'plot' 16 } 17 }, { 18 'regex': { 19 'query': '([0-9]{4})', 20 'path': 'plot', 21 'allowAnalyzedField': True 22 } 23 } 24 ], 25 'mustNot': [ 26 { 27 'text': { 28 'query': [ 29 'Comedy', 'Romance' 30 ], 31 'path': 'genres' 32 } 33 }, { 34 'text': { 35 'query': [ 36 'Beach', 'Snow' 37 ], 38 'path': 'title' 39 } 40 } 41 ] 42 } 43 } 44 }, { 45 '$project': { 46 'title': 1, 47 'plot': 1, 48 'genres': 1, 49 '_id': 0 50 } 51 } 52 ]) 53 54 for i in result: 55 print(i) 运行以下命令来查询您的集合:
python complex-query.py {'plot': 'A modern aircraft carrier is thrown back in time to 1941 near Hawaii, just hours before the Japanese attack on Pearl Harbor.', 'genres': ['Action', 'Sci-Fi'], 'title': 'The Final Countdown'} {'plot': "Follows John McCain's 2008 presidential campaign, from his selection of Alaska Governor Sarah Palin as his running mate to their ultimate defeat in the general election.", 'genres': ['Biography', 'Drama', 'History'], 'title': 'Game Change'} {'plot': 'A devastating and heartrending take on grizzly bear activists Timothy Treadwell and Amie Huguenard, who were killed in October of 2003 while living among grizzlies in Alaska.', 'genres': ['Documentary', 'Biography'], 'title': 'Grizzly Man'} {'plot': 'Truman Korovin is a lonely, sharp-witted cab driver in Fairbanks, Alaska, 1980. The usual routine of picking up fares and spending his nights at his favorite bar, the Boatel, is disrupted ...', 'genres': ['Drama'], 'title': 'Chronic Town'}
后续步骤
现在您已经运行了一些查询,请查看 Atlas Search 文档,详细了解您可以运行的不同操作符和其他查询。更多查询示例请参阅 Atlas Search文档。
喜欢通过观看视频来学习?
请继续观看本视频教程,该视频演示了如何为 Restaurant Finder 演示应用程序构建 Atlas Search 查询,该应用程序也可在 www.atlassearchrestaurants.com 上获取。
时长:20 分钟