如何使用日期范围筛选器运行 Atlas Search 查询
本教程介绍如何在 sample_mflix.movies
集合上创建具有动态映射的索引。它展示了如何使用 范围和接近操作符对 released
字段运行复合查询。它将引导您完成以下步骤:
为
sample_mflix.movies
集合设置具有动态映射的 Atlas Search 索引。针对
sample_mflix.movies
集合中的released
字段运行 Atlas Search 复合查询。
开始之前,请确保 Atlas 集群满足先决条件中所述的要求。
要创建 Atlas Search 索引,您必须拥有 Project Data Access Admin
或更高的项目访问权限。
使用动态映射创建 Atlas Search 索引
在本部分中,我们将创建一个 Atlas Search 索引,该索引使用动态映射为sample_mflix.movies
集合的字段编制索引。
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 页面。
输入 Index Name(索引名称),然后设置 Database and Collection(数据库和集合)。
在 Index Name 字段中输入
date-range-tutorial
。如果将索引命名为
default
,则在使用 $search 管道阶段时无需指定index
参数。如果您为索引指定了自定义名称,则必须在index
参数中指定此名称。在 Database and Collection(数据库和集合)部分中找到
sample_mflix
数据库,然后选择movies
集合。
指定索引定义。
您可以创建使用动态映射或静态映射的 Atlas Search 索引。要了解有关动态和静态映射的更多信息,请参阅静态和动态映射。
以下索引定义对 movies
集合中的支持类型字段动态创建索引。您可以使用 Atlas Search Visual Editor 或 Atlas Search JSON Editor 在 Atlas 用户界面中创建索引。
可视化编辑器
单击 Next(连接)。
查看
movies
集合的"date-range-tutorial"
索引定义。
JSON 编辑器
单击 Next(连接)。
查看索引定义。
索引定义应类似于以下内容:
{ "mappings": { "dynamic": true } } 上述索引定义对
movies
集合中每个文档中的支持类型字段动态创建索引。单击 Next(连接)。
运行复合查询
➤ 使用 Select your language(选择您的语言)下拉菜单设置此页面上示例的语言。
您可以使用复合运算符将两个或多个运算符和子句组合成一个查询。本教程使用复合运算符子句搜索指定日期范围内的电影。在本部分中,连接到您的 Atlas 集群并使用复合运算符对 sample_mflix.movies
中的 released
字段运行示例查询。
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 compound
查询。
以下示例使用带有子查询的 compound
操作符来搜索 2010
到 2015
年之间的电影。该查询使用以下子句:
一个
must
子句,用于搜索在2015-01-01
和2015-12-31
之间上映的电影should
子句,用于指定优先选择在2012-07-01
附近上映的电影,中枢距离为 1 个月
该查询包括一个 $limit
阶段,将输出限制为 6 个结果,以及一个 $project
阶段:
排除
title
、released
和genres
字段以外的所有字段添加字段
score
将以下查询复制并粘贴到 Query Editor 中,然后点击 Query Editor 中的 Search 按钮。
1 [ 2 { 3 $search: { 4 "index": "date-range-tutorial", 5 "compound": { 6 "must": [{ 7 "range": { 8 "path": "released", 9 "gt": ISODate("2015-01-01T00:00:00.000Z"), 10 "lt": ISODate("2015-12-31T00:00:00.000Z") 11 } 12 }], 13 "should": [{ 14 "near": { 15 "path": "released", 16 "origin": ISODate("2015-07-01T00:00:00.000+00:00"), 17 "pivot": 2629800000 18 } 19 }] 20 } 21 } 22 } 23 ]
SCORE: 2 _id: "573a13c4f29313caabd6c383" fullplot: "When John Connor (Jason Clarke), leader of the human resistance, sends…" imdb: Object year: 2015 ... released: 2015-07-01T00:00:00.000+00:00 ... SCORE: 2 _id: "573a13d9f29313caabdaa9e2" fullplot: "Three years after Mike bowed out of the stripper life at the top of hi…" imdb: Object year: 2015 ... released: 2015-07-01T00:00:00.000+00:00 ... SCORE: 2 _id: "573a13e9f29313caabdcd223" plot: "A documentary about the power of transformation told through the eyes …" genres: Array runtime: 87 ... released: 2015-07-01T00:00:00.000+00:00 ... SCORE: 2 _id: "573a13f4f29313caabde1138" plot: "Dedicated home care nurse Vlasta lives for her husband Lada, her daugh…" genres: Array runtime: 92 ... released: 2015-07-01T00:00:00.000+00:00 ... SCORE: 2 _id: "573a13f9f29313caabdeb320" plot: "For anyone who has not fully understood the controversial Bitcoin yet,…" genres: Array runtime: 60 ... released: 2015-07-01T00:00:00.000+00:00 ... SCORE: 1.9681909084320068 _id: "573a13c2f29313caabd67986" plot: "A man wakes up alone in the middle of the desert with a black hood on …" genres: Array runtime: 90 ... released: 2015-07-02T00:00:00.000+00:00 ... SCORE: 1.9681909084320068 _id: "573a13f4f29313caabde14cf" plot: "In 1836 the Danish romantic visionary Wulff travels to Africa to creat…" genres: Array runtime: 114 ... released: 2015-07-02T00:00:00.000+00:00 ... SCORE: 1.9383430480957031 _id: "573a13d6f29313caabd9f77d" plot: "The plot of the film has a grandfather telling his grand kids the stor…" genres: Array runtime: 78 ... released: 2015-07-03T00:00:00.000+00:00 ... SCORE: 1.9383430480957031 _id: "573a13e3f29313caabdbfb00" plot: "The story of Amy Winehouse in her own words, featuring unseen archival…" genres: Array runtime: 128 ... released: 2015-07-02T00:00:00.000+00:00 ... SCORE: 1.9383430480957031 _id: "573a13e9f29313caabdcbe1e" plot: "A modern day train hopper fighting to become a successful musician, an…" genres: Array runtime: 90 ... released: 2015-07-02T00:00:00.000+00:00 ...
展开查询结果。
Search Tester 可能不会显示其所返回文档的所有字段。要查看所有字段,包括在查询路径中指定的字段,请展开结果中的文档。
对于该查询,排名靠前的结果会在 7 月上映,因为 should
子句指定了对 7 月前后上映的电影的偏好。
对 movies
集合运行包含三个子句的 Atlas Search compound
查询。
以下示例是对上一个示例的补充。
除了 must
和 should
子句之外,此查询还包含一个 mustNot
子句,用于指定结果中不得包含 documentary
类型的电影。
1 [ 2 { 3 $search: { 4 "index": "date-range-tutorial", 5 "compound": { 6 "must": [{ 7 "range": { 8 "path": "released", 9 "gt": ISODate("2015-01-01T00:00:00.000Z"), 10 "lt": ISODate("2015-12-31T00:00:00.000Z") 11 } 12 }], 13 "should": [{ 14 "near": { 15 "path": "released", 16 "origin": ISODate("2015-07-01T00:00:00.000+00:00"), 17 "pivot": 2629800000 18 } 19 }], 20 "mustNot": [{ 21 "text": { 22 "query": "documentary", 23 "path": "genres" 24 } 25 }] 26 } 27 } 28 } 29 ]
SCORE: 2 _id: "573a13c4f29313caabd6c383" fullplot: "When John Connor (Jason Clarke), leader of the human resistance, sends…" imdb: Object year: 2015 ... genres: 0: "Action" 1: "Adventure" 2: "Sci-Fi" ... released: 2015-07-01T00:00:00.000+00:00 ... SCORE: 2 _id: "573a13d9f29313caabdaa9e2" fullplot: "Three years after Mike bowed out of the stripper life at the top of hi…" imdb: Object year: 2015 ... genres: 0: "Comedy" 1: "Drama" 2: "Music" ... released: 2015-07-01T00:00:00.000+00:00 ... SCORE: 2 _id: "573a13f4f29313caabde1138" plot: "Dedicated home care nurse Vlasta lives for her husband Lada, her daugh…" genres: 0: "Comedy" 1: "Drama" runtime: 92 ... released: 2015-07-01T00:00:00.000+00:00 ... SCORE: 1.9681909084320068 _id: "573a13c2f29313caabd67986" plot: "A man wakes up alone in the middle of the desert with a black hood on …" genres: 0: "Drama" 1: "Mystery" 2: "Sci-Fi" runtime: 90 ... released: 2015-07-02T00:00:00.000+00:00 ... SCORE: 1.9681909084320068 _id: "573a13f4f29313caabde14cf" plot: "In 1836 the Danish romantic visionary Wulff travels to Africa to creat…" genres: 0: "Drama" 1: "History" 2: "Romance" runtime: 114 ... released: 2015-07-02T00:00:00.000+00:00 ... SCORE: 1.9383430480957031 _id: "573a13d6f29313caabd9f77d" plot: "The plot of the film has a grandfather telling his grand kids the stor…" genres: 0: "Animation" 1: "Family" runtime: 78 ... released: 2015-07-03T00:00:00.000+00:00 ... SCORE: 1.9383430480957031 _id: "573a13e9f29313caabdcbe1e" plot: "A modern day train hopper fighting to become a successful musician, an…" genres: 0: "Drama" runtime: 90 ... released: 2015-07-03T00:00:00.000+00:00 ... SCORE: 1.9383430480957031 _id: "573a13e9f29313caabdccb5b" plot: "A fancy garden party turns into upper class prey when a colony of kill…" genres: 0: "Comedy" 1: "Horror" runtime: 87 ... released: 2015-07-03T00:00:00.000+00:00 ... SCORE: 1.9102803468704224 _id: "573a13faf29313caabdec74f" countries: Array genres: 0: "Drama" runtime: 104 ... released: 2015-07-03T00:00:00.000+00:00 ... SCORE: 1.8838474750518799 _id: "573a13eef29313caabdd531d" plot: "A fantasy love story that drifts between this world and heaven. Chasuk…" genres: 0: "Comdedy" countries: Array ... released: 2015-06-27T00:00:00.000+00:00 ...
展开查询结果。
Search Tester 可能不会显示其所返回文档的所有字段。要查看所有字段,包括在查询路径中指定的字段,请展开结果中的文档。
对于该查询,排名靠前的结果会在 7 月上映,因为 should
子句指定了对 7 月前后上映的电影的偏好。
通过 mongosh
连接到您的集群。
在终端窗口中打开mongosh
并连接到集群。 有关连接的详细说明,请参阅通过mongosh
连接。
使用 sample_mflix
数据库。
在 mongosh
提示符下运行以下命令:
use sample_mflix
对 movies
集合运行包含两个子句的 Atlas Search compound
查询。
以下示例使用带有子查询的 compound
操作符来搜索 2010
到 2015
年之间的电影。该查询使用以下子句:
一个
must
子句,用于搜索在2015-01-01
和2015-12-31
之间上映的电影should
子句,用于指定优先选择在2012-07-01
附近上映的电影,中枢距离为 1 个月
该查询包括一个 $limit
阶段,将输出限制为 6 个结果,以及一个 $project
阶段:
排除
title
、released
和genres
字段以外的所有字段添加字段
score
db.movies.aggregate([ { "$search": { "index": "date-range-tutorial", "compound": { "must": [{ "range": { "path": "released", "gt": ISODate("2015-01-01T00:00:00.000Z"), "lt": ISODate("2015-12-31T00:00:00.000Z") } }], "should": [{ "near": { "path": "released", "origin": ISODate("2015-07-01T00:00:00.000+00:00"), "pivot": 2629800000 } }] } } }, { "$limit": 6 }, { "$project": { "_id": 0, "title": 1, "released": 1, "genres": 1, "score": { "$meta": "searchScore" } } } ])
[ { "genres": [ "Action", "Adventure", "Sci-Fi" ], "title": "Terminator Genisys", "released": ISODate("2015-07-01T00:00:00.000Z"), "score": 2 }, { "genres": [ "Comedy", "Drama", "Music" ], "title": "Magic Mike XXL", "released": ISODate("2015-07-01T00:00:00.000Z"), "score": 2 }, { "genres": [ "Documentary", "Biography", "Drama" ], "title": "Mala Mala", "released": ISODate("2015-07-01T00:00:00.000Z"), "score": 2 }, { "genres": [ "Comedy", "Drama" ], "title": "Home Care", "released": ISODate("2015-07-01T00:00:00.000Z"), "score": 2 }, { "genres": [ "Documentary", "News" ], "title": "Bitcoin: The End of Money as We Know It", "released": ISODate("2015-07-01T00:00:00.000Z"), "score": 2 }, { "genres": [ "Drama", "Mystery", "Sci-Fi" ], "title": "Pig", "released": ISODate("2015-07-02T00:00:00.000Z"), "score": 1.9681909084320068 } ]
对于该查询,排名靠前的结果会在 7 月上映,因为 should
子句指定了对 7 月前后上映的电影的偏好。
对 movies
集合运行包含三个子句的 Atlas Search compound
查询。
以下示例是对上一个示例的补充。
除了 must
和 should
子句之外,此查询还包含一个 mustNot
子句,用于指定结果中不得包含 documentary
类型的电影。
db.movies.aggregate([ { "$search": { "compound": { "must": [{ "range": { "path": "released", "gt": ISODate("2015-01-01T00:00:00.000Z"), "lt": ISODate("2015-12-31T00:00:00.000Z") } }], "should": [{ "near": { "path": "released", "origin": ISODate("2015-07-01T00:00:00.000+00:00"), "pivot": 2629800000 } }], "mustNot": [{ "text": { "query": "documentary", "path": "genres" } }] } } }, { "$limit": 10 }, { "$project": { "_id": 0, "title": 1, "released": 1, "genres": 1, "score": { "$meta": "searchScore" } } } ])
[ { "genres": [ "Action", "Adventure", "Sci-Fi" ], "title": "Terminator Genisys", "released": ISODate("2015-07-01T00:00:00.000Z"), "score": 2 }, { "genres": [ "Comedy", "Drama", "Music" ], "title": "Magic Mike XXL", "released": ISODate("2015-07-01T00:00:00.000Z"), "score": 2 }, { "genres": [ "Comedy", "Drama" ], "title": "Home Care", "released": ISODate("2015-07-01T00:00:00.000Z"), "score": 2 }, { "genres": [ "Drama", "Mystery", "Sci-Fi" ], "title": "Pig", "released": ISODate("2015-07-02T00:00:00.000Z"), "score": 1.9681909084320068 }, { "genres": [ "Drama", "History", "Romance" ], "title": "Gold Coast", "released": ISODate("2015-07-02T00:00:00.000Z"), "score": 1.9681909084320068 }, { "genres": [ "Animation", "Family" ], "title": "Zarafa", "released": ISODate("2015-07-03T00:00:00.000Z"), "score": 1.9383430480957031 } ]
对于该查询,排名靠前的结果会在 7 月上映,因为 should
子句指定了对 7 月前后上映的电影的偏好。
在 MongoDB Compass 中连接到您的集群。
打开 MongoDB Compass 并连接到您的集群。有关连接的详细说明,请参阅通过 Compass 连接。
对 movies
集合运行包含两个子句的 Atlas Search compound
查询。
以下示例使用带有子查询的 compound
操作符来搜索 2010
到 2015
年之间的电影。该查询使用以下子句:
一个
must
子句,用于搜索在2015-01-01
和2015-12-31
之间上映的电影should
子句,用于指定优先选择在2012-07-01
附近上映的电影,中枢距离为 1 个月
该查询包括一个 $limit
阶段,将输出限制为 6 个结果,以及一个 $project
阶段:
排除
title
、released
和genres
字段以外的所有字段添加字段
score
若要在 MongoDB Compass 中运行此查询:
单击 Aggregations 标签页。
单击 Select...,然后从下拉菜单中选择阶段并为该阶段添加查询,以配置以下每个管道阶段。单击 Add Stage 以添加其他阶段。
管道阶段 | 查询 | |||||||||||||||||||
---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|
$search |
| |||||||||||||||||||
$limit |
| |||||||||||||||||||
$project |
|
如果启用了 Auto Preview,MongoDB Compass 将在 $project
管道阶段旁边显示以下文档:
{ "genres": [ "Action", "Adventure", "Sci-Fi" ], "title": "Terminator Genisys", "released": ISODate("2015-07-01T00:00:00.000Z"), "score": 2 }, { "genres": [ "Comedy", "Drama", "Music" ], "title": "Magic Mike XXL", "released": ISODate("2015-07-01T00:00:00.000Z"), "score": 2 }, { "genres": [ "Documentary", "Biography", "Drama" ], "title": "Mala Mala", "released": ISODate("2015-07-01T00:00:00.000Z"), "score": 2 }, { "genres": [ "Comedy", "Drama" ], "title": "Home Care", "released": ISODate("2015-07-01T00:00:00.000Z"), "score": 2 }, { "genres": [ "Documentary", "News" ], "title": "Bitcoin: The End of Money as We Know It", "released": ISODate("2015-07-01T00:00:00.000Z"), "score": 2 }, { "genres": [ "Drama", "Mystery", "Sci-Fi" ], "title": "Pig", "released": ISODate("2015-07-02T00:00:00.000Z"), "score": 1.9681909084320068 }
对于该查询,排名靠前的结果会在 7 月上映,因为 should
子句指定了对 7 月前后上映的电影的偏好。
对 movies
集合运行包含三个子句的 Atlas Search compound
查询。
以下示例是对上一个示例的补充。
除了 must
和 should
子句之外,此查询还包含一个 mustNot
子句,用于指定结果中不得包含 documentary
类型的电影。
若要在 MongoDB Compass 中运行此查询:
单击 Aggregations 标签页。
单击 Select...,然后从下拉菜单中选择阶段并为该阶段添加查询,以配置以下每个管道阶段。单击 Add Stage 以添加其他阶段。
管道阶段 | 查询 | |||||||||||||||||||||||||
---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|
$search |
| |||||||||||||||||||||||||
$limit |
| |||||||||||||||||||||||||
$project |
|
如果启用了 Auto Preview,MongoDB Compass 将在 $project
管道阶段旁边显示以下文档:
{ "genres": [ "Action", "Adventure", "Sci-Fi" ], "title": "Terminator Genisys", "released": ISODate("2015-07-01T00:00:00.000Z"), "score": 2 }, { "genres": [ "Comedy", "Drama", "Music" ], "title": "Magic Mike XXL", "released": ISODate("2015-07-01T00:00:00.000Z"), "score": 2 }, { "genres": [ "Comedy", "Drama" ], "title": "Home Care", "released": ISODate("2015-07-01T00:00:00.000Z"), "score": 2 }, { "genres": [ "Drama", "Mystery", "Sci-Fi" ], "title": "Pig", "released": ISODate("2015-07-02T00:00:00.000Z"), "score": 1.9681909084320068 }, { "genres": [ "Drama", "History", "Romance" ], "title": "Gold Coast", "released": ISODate("2015-07-02T00:00:00.000Z"), "score": 1.9681909084320068 }, { "genres": [ "Animation", "Family" ], "title": "Zarafa", "released": ISODate("2015-07-03T00:00:00.000Z"), "score": 1.9383430480957031 }
对于该查询,排名靠前的结果会在 7 月上映,因为 should
子句指定了对 7 月前后上映的电影的偏好。
使用 compound
操作符创建并运行 Atlas Search 查询,在 Program.cs
文件中包含两个子句。
将
Program.cs
文件的内容替换为以下代码。此代码示例将执行以下任务:
导入
mongodb
包和依赖项。建立与您的 Atlas 集群的连接。
使用以下
compound
操作符子句对该集合进行查询:一个
must
子句,用于搜索在2015-01-01
和2015-12-31
之间上映的电影should
子句,用于指定优先选择在2012-07-01
附近上映的电影,中枢距离为 1 个月
该查询包括一个
$limit
阶段,将输出限制为 6 个结果,以及一个$project
阶段:排除
title
、released
和genres
字段以外的所有字段添加字段
score
遍历游标以打印与查询匹配的文档。
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 DateRangeExample 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 compound query 23 var startDate = new DateTime(2015, 01, 01, 0, 0, 0, DateTimeKind.Utc); 24 var endDate = new DateTime(2015, 12, 31, 0, 0, 0, DateTimeKind.Utc); 25 var nearDate = new DateTime(2015, 07, 01, 0, 0, 0, DateTimeKind.Utc); 26 27 // define and run pipeline 28 var results = moviesCollection.Aggregate() 29 .Search(Builders<MovieDocument>.Search.Compound() 30 .Must(Builders<MovieDocument>.Search.Range(movie => movie.Released, SearchRangeBuilder.Gt(startDate).Lt(endDate))) 31 .Should(Builders<MovieDocument>.Search.Near(movie => movie.Released, nearDate, 2629800000)), 32 indexName: "date-range-tutorial") 33 .Project<MovieDocument>(Builders<MovieDocument>.Projection 34 .Include(movie => movie.Genres) 35 .Include(movie => movie.Released) 36 .Include(movie => movie.Title) 37 .Exclude(movie => movie.Id) 38 .MetaSearchScore(movie => movie.Score)) 39 .Limit(6) 40 .ToList(); 41 42 // print results 43 foreach (var movie in results) 44 { 45 Console.WriteLine(movie.ToJson()); 46 } 47 } 48 } 49 50 [ ]51 public class MovieDocument 52 { 53 [ ]54 public ObjectId Id { get; set; } 55 public string [] Genres { get; set; } 56 public DateTime Released { get; set; } 57 public string Title { get; set; } 58 public double Score { get; set; } 59 } 在运行示例之前,请将
<connection-string>
替换为 Atlas 连接字符串。确保您的连接字符串包含数据库用户的档案。要了解详情,请参阅通过驱动程序连接。编译并运行
Program.cs
文件。dotnet run date-range-example.csproj { "genres" : ["Action", "Adventure", "Sci-Fi"], "released" : ISODate("2015-07-01T00:00:00Z"), "title" : "Terminator Genisys", "score" : 2.0 } { "genres" : ["Comedy", "Drama", "Music"], "released" : ISODate("2015-07-01T00:00:00Z"), "title" : "Magic Mike XXL", "score" : 2.0 } { "genres" : ["Documentary", "Biography", "Drama"], "released" : ISODate("2015-07-01T00:00:00Z"), "title" : "Mala Mala", "score" : 2.0 } { "genres" : ["Comedy", "Drama"], "released" : ISODate("2015-07-01T00:00:00Z"), "title" : "Home Care", "score" : 2.0 } { "genres" : ["Documentary", "News"], "released" : ISODate("2015-07-01T00:00:00Z"), "title" : "Bitcoin: The End of Money as We Know It", "score" : 2.0 } { "genres" : ["Drama", "Mystery", "Sci-Fi"], "released" : ISODate("2015-07-02T00:00:00Z"), "title" : "Pig", "score" : 1.9681909084320068 }
对于该查询,排名靠前的结果会在 7 月上映,因为 should
子句指定了对 7 月前后上映的电影的偏好。
使用 compound
操作符创建并运行 Atlas Search 查询,在 Program.cs
文件中包含三个子句。
将
Program.cs
文件的内容替换为以下代码。此代码示例将执行以下任务:
导入
mongodb
包和依赖项。建立与您的 Atlas 集群的连接。
对上一个示例进行补充。
除了
must
和should
子句之外,此查询还包含一个mustNot
子句,用于指定结果中不得包含documentary
类型的电影。遍历游标以打印与查询匹配的文档。
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 DateRangeComplexExample 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 compound query 23 var startDate = new DateTime(2015, 01, 01, 0, 0, 0, DateTimeKind.Utc); 24 var endDate = new DateTime(2015, 12, 31, 0, 0, 0, DateTimeKind.Utc); 25 var nearDate = new DateTime(2015, 07, 01, 0, 0, 0, DateTimeKind.Utc); 26 27 // define and run pipeline 28 var results = moviesCollection.Aggregate() 29 .Search(Builders<MovieDocument>.Search.Compound() 30 .Must(Builders<MovieDocument>.Search.Range(movie => movie.Released, SearchRangeBuilder.Gt(startDate).Lt(endDate))) 31 .Should(Builders<MovieDocument>.Search.Near(movie => movie.Released, nearDate, 2629800000)) 32 .MustNot(Builders<MovieDocument>.Search.Text(movie => movie.Genres, "Documentary")), 33 indexName: "date-range-tutorial") 34 .Project<MovieDocument>(Builders<MovieDocument>.Projection 35 .Include(movie => movie.Genres) 36 .Include(movie => movie.Released) 37 .Include(movie => movie.Title) 38 .Exclude(movie => movie.Id) 39 .MetaSearchScore(movie => movie.Score)) 40 .Limit(6) 41 .ToList(); 42 43 // print results 44 foreach (var movie in results) 45 { 46 Console.WriteLine(movie.ToJson()); 47 } 48 } 49 } 50 51 [ ]52 public class MovieDocument 53 { 54 [ ]55 public ObjectId Id { get; set; } 56 public string [] Genres { get; set; } 57 public DateTime Released { get; set; } 58 public string Title { get; set; } 59 public double Score { get; set; } 60 } 在运行示例之前,请将
<connection-string>
替换为 Atlas 连接字符串。确保您的连接字符串包含数据库用户的档案。要了解详情,请参阅通过驱动程序连接。编译并运行
Program.cs
文件。dotnet run date-range-example.csproj { "genres" : ["Action", "Adventure", "Sci-Fi"], "released" : ISODate("2015-07-01T00:00:00Z"), "title" : "Terminator Genisys", "score" : 2.0 } { "genres" : ["Comedy", "Drama", "Music"], "released" : ISODate("2015-07-01T00:00:00Z"), "title" : "Magic Mike XXL", "score" : 2.0 } { "genres" : ["Comedy", "Drama"], "released" : ISODate("2015-07-01T00:00:00Z"), "title" : "Home Care", "score" : 2.0 } { "genres" : ["Drama", "Mystery", "Sci-Fi"], "released" : ISODate("2015-07-02T00:00:00Z"), "title" : "Pig", "score" : 1.9681909084320068 } { "genres" : ["Drama", "History", "Romance"], "released" : ISODate("2015-07-02T00:00:00Z"), "title" : "Gold Coast", "score" : 1.9681909084320068 } { "genres" : ["Animation", "Family"], "released" : ISODate("2015-07-03T00:00:00Z"), "title" : "Zarafa", "score" : 1.9383430480957031 }
对于该查询,排名靠前的结果会在 7 月上映,因为 should
子句指定了对 7 月前后上映的电影的偏好。
对 movies
集合运行包含两个子句的 Atlas Search compound
查询。
创建一个名为
date-range.go
的文件。将以下代码复制并粘贴到
date-range.go
文件。此代码示例将执行以下任务:
导入
mongodb
包和依赖项。建立与您的 Atlas 集群的连接。
使用以下
compound
操作符子句对该集合进行查询:一个
must
子句,用于搜索在2015-01-01
和2015-12-31
之间上映的电影should
子句,用于指定优先选择在2012-07-01
附近上映的电影,中枢距离为 1 个月
该查询包括一个
$limit
阶段,将输出限制为 6 个结果,以及一个$project
阶段:排除
title
、released
和genres
字段以外的所有字段添加字段
score
遍历游标以打印与查询匹配的文档。
1 package main 2 3 import ( 4 "context" 5 "fmt" 6 "time" 7 8 "go.mongodb.org/mongo-driver/bson" 9 "go.mongodb.org/mongo-driver/mongo" 10 "go.mongodb.org/mongo-driver/mongo/options" 11 ) 12 13 func main() { 14 // connect to your Atlas cluster 15 client, err := mongo.Connect(context.TODO(), options.Client().ApplyURI("<connection-string>")) 16 if err != nil { 17 panic(err) 18 } 19 defer client.Disconnect(context.TODO()) 20 21 // set namespace 22 collection := client.Database("sample_mflix").Collection("movies") 23 24 // define pipeline stages 25 searchStage := bson.D{{"$search", bson.M{ 26 "index": "date-range-tutorial", 27 "compound": bson.M{ 28 "must": bson.M{ 29 "range": bson.M{ 30 "path": "released", 31 "gt": time.Date(2015, time.January, 1, 0, 0, 0, 0, time.UTC), 32 "lt": time.Date(2015, time.December, 31, 0, 0, 0, 0, time.UTC), 33 }}, 34 "should": bson.D{ 35 {"near", bson.M{ 36 "path": "released", 37 "origin": time.Date(2015, time.July, 1, 0, 0, 0, 0, time.UTC), 38 "pivot": 2629800000, 39 }}}, 40 }}}} 41 projectStage := bson.D{{"$project", bson.D{{"_id", 0}, {"title", 1}, {"released", 1}, {"genres", 1}, {"score", bson.D{{"$meta", "searchScore"}}}}}} 42 limitStage := bson.D{{"$limit", 6}} 43 44 // run pipeline 45 cursor, err := collection.Aggregate(context.TODO(), mongo.Pipeline{searchStage, projectStage, limitStage}) 46 if err != nil { 47 panic(err) 48 } 49 50 // print results 51 var results []bson.D 52 if err = cursor.All(context.TODO(), &results); err != nil { 53 panic(err) 54 } 55 for _, result := range results { 56 fmt.Println(result) 57 } 58 } 在运行示例之前,请将
<connection-string>
替换为 Atlas 连接字符串。确保您的连接字符串包含数据库用户的档案。要了解详情,请参阅通过驱动程序连接。运行以下命令来查询您的集合:
go run date-range.go [{genres [Action Adventure Sci-Fi]} {title Terminator Genisys} {released 1435708800000} {score 2}] [{genres [Comedy Drama Music]} {title Magic Mike XXL} {released 1435708800000} {score 2}] [{genres [Documentary Biography Drama]} {title Mala Mala} {released 1435708800000} {score 2}] [{genres [Comedy Drama]} {title Home Care} {released 1435708800000} {score 2}] [{genres [Documentary News]} {title Bitcoin: The End of Money as We Know It} {released 1435708800000} {score 2}] [{genres [Drama Mystery Sci-Fi]} {title Pig} {released 1435795200000} {score 1.9681909084320068}] 对于该查询,排名靠前的结果会在 7 月上映,因为
should
子句指定了对 7 月前后上映的电影的偏好。
对 movies
集合运行包含三个子句的 Atlas Search compound
查询。
创建一个名为
date-range-complex.go
的文件。将以下代码复制并粘贴到
date-range-complex.go
文件。此代码示例将执行以下任务:
导入
mongodb
包和依赖项。建立与您的 Atlas 集群的连接。
对上一个示例进行补充。
除了
must
和should
子句之外,此查询还包含一个mustNot
子句,用于指定结果中不得包含documentary
类型的电影。遍历游标以打印与查询匹配的文档。
1 package main 2 3 import ( 4 "context" 5 "fmt" 6 "time" 7 8 "go.mongodb.org/mongo-driver/bson" 9 "go.mongodb.org/mongo-driver/mongo" 10 "go.mongodb.org/mongo-driver/mongo/options" 11 ) 12 13 func main() { 14 // connect to your Atlas cluster 15 client, err := mongo.Connect(context.TODO(), options.Client().ApplyURI("<connection-string>")) 16 if err != nil { 17 panic(err) 18 } 19 defer client.Disconnect(context.TODO()) 20 21 // set namespace 22 collection := client.Database("sample_mflix").Collection("movies") 23 24 // define pipeline stages 25 searchStage := bson.D{{"$search", bson.M{ 26 "index": "date-range-tutorial", 27 "compound": bson.M{ 28 "must": bson.M{ 29 "range": bson.M{ 30 "path": "released", 31 "gt": time.Date(2015, time.January, 1, 0, 0, 0, 0, time.UTC), 32 "lt": time.Date(2015, time.December, 31, 0, 0, 0, 0, time.UTC), 33 }}, 34 "should": bson.D{ 35 {"near", bson.M{ 36 "path": "released", 37 "origin": time.Date(2015, time.July, 1, 0, 0, 0, 0, time.UTC), 38 "pivot": 2629800000, 39 }}}, 40 "mustNot": bson.D{ 41 {"text", bson.M{ 42 "path": "genres", "query": "Documentary", 43 }}}, 44 }}}} 45 projectStage := bson.D{{"$project", bson.D{{"_id", 0}, {"title", 1}, {"released", 1}, {"genres", 1}, {"score", bson.D{{"$meta", "searchScore"}}}}}} 46 limitStage := bson.D{{"$limit", 6}} 47 48 // run pipeline 49 cursor, err := collection.Aggregate(context.TODO(), mongo.Pipeline{searchStage, projectStage, limitStage}) 50 if err != nil { 51 panic(err) 52 } 53 54 // print results 55 var results []bson.D 56 if err = cursor.All(context.TODO(), &results); err != nil { 57 panic(err) 58 } 59 for _, result := range results { 60 fmt.Println(result) 61 } 62 } 在运行示例之前,请将
<connection-string>
替换为 Atlas 连接字符串。确保您的连接字符串包含数据库用户的档案。要了解详情,请参阅通过驱动程序连接。运行以下命令来查询您的集合:
go run date-range-complex.go [{genres [Action Adventure Sci-Fi]} {title Terminator Genisys} {released 1435708800000} {score 2}] [{genres [Comedy Drama Music]} {title Magic Mike XXL} {released 1435708800000} {score 2}] [{genres [Comedy Drama]} {title Home Care} {released 1435708800000} {score 2}] [{genres [Drama Mystery Sci-Fi]} {title Pig} {released 1435795200000} {score 1.9681909084320068}] [{genres [Drama History Romance]} {title Gold Coast} {released 1435795200000} {score 1.9681909084320068}] [{genres [Animation Family]} {title Zarafa} {released 1435881600000} {score 1.9383430480957031}] 对于该查询,排名靠前的结果会在 7 月上映,因为
should
子句指定了对 7 月前后上映的电影的偏好。
对 movies
集合运行包含两个子句的 Atlas Search compound
查询。
创建一个名为
DateRange.java
的文件。将以下代码复制并粘贴到
DateRange.java
文件。此代码示例将执行以下任务:
导入
mongodb
包和依赖项。建立与您的 Atlas 集群的连接。
使用以下
compound
操作符子句对该集合进行查询:一个
must
子句,用于搜索在2015-01-01
和2015-12-31
之间上映的电影should
子句,用于指定优先选择在2012-07-01
附近上映的电影,中枢距离为 1 个月
该查询包括一个
$limit
阶段,将输出限制为 6 个结果,以及一个$project
阶段:排除
title
、released
和genres
字段以外的所有字段添加字段
score
遍历游标以打印与查询匹配的文档。
1 import java.util.Arrays; 2 import java.util.List; 3 4 import static com.mongodb.client.model.Aggregates.limit; 5 import static com.mongodb.client.model.Aggregates.project; 6 import static com.mongodb.client.model.Projections.*; 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 import java.time.Instant; 14 import java.util.Date; 15 16 public class DateRange { 17 public static void main( String[] args ) { 18 // define clauses 19 List<Document> mustClauses = 20 List.of( new Document( 21 "range", new Document("path", "released") 22 .append("gt", Date.from(Instant.parse("2015-01-01T00:00:00.000Z"))) 23 .append("lt", Date.from(Instant.parse("2015-12-31T00:00:00.000Z"))))); 24 List<Document> shouldClauses = 25 List.of( 26 new Document( 27 "near", 28 new Document("pivot", 2629800000L) 29 .append("path", "released") 30 .append("origin", Date.from(Instant.parse("2015-07-01T00:00:00.000+00:00"))))); 31 // define query 32 Document agg = 33 new Document( "$search", 34 new Document("index", "date-range-tutorial") 35 .append( "compound", 36 new Document().append("must", mustClauses) 37 .append("should", shouldClauses))); 38 // specify connection 39 String uri = "<connection-string>"; 40 41 // establish connection and set namespace 42 try (MongoClient mongoClient = MongoClients.create(uri)) { 43 MongoDatabase database = mongoClient.getDatabase("sample_mflix"); 44 MongoCollection<Document> collection = database.getCollection("movies"); 45 46 // run query and print results 47 collection.aggregate(Arrays.asList(agg, 48 project(fields( 49 excludeId(), 50 include("title", "released", "genres"), 51 computed("score", new Document("$meta", "searchScore")))), 52 limit(6))) 53 .forEach(doc -> System.out.println(doc.toJson())); 54 } 55 } 56 } 注意
要在 Maven 环境中运行示例代码,请将以下代码添加到文件中的 import 语句上方。
package com.mongodb.drivers; 在运行示例之前,请将
<connection-string>
替换为 Atlas 连接字符串。确保您的连接字符串包含数据库用户的档案。要了解详情,请参阅通过驱动程序连接。编译并运行
DateRange.java
文件。javac DateRange.java java DateRange {"genres": ["Action", "Adventure", "Sci-Fi"], "title": "Terminator Genisys", "released": {"$date": "2015-07-01T00:00:00Z"}, "score": 2.0} {"genres": ["Comedy", "Drama", "Music"], "title": "Magic Mike XXL", "released": {"$date": "2015-07-01T00:00:00Z"}, "score": 2.0} {"genres": ["Documentary", "Biography", "Drama"], "title": "Mala Mala", "released": {"$date": "2015-07-01T00:00:00Z"}, "score": 2.0} {"genres": ["Comedy", "Drama"], "title": "Home Care", "released": {"$date": "2015-07-01T00:00:00Z"}, "score": 2.0} {"genres": ["Documentary", "News"], "title": "Bitcoin: The End of Money as We Know It", "released": {"$date": "2015-07-01T00:00:00Z"}, "score": 2.0} {"genres": ["Drama", "Mystery", "Sci-Fi"], "title": "Pig", "released": {"$date": "2015-07-02T00:00:00Z"}, "score": 1.9681909084320068}
对于该查询,排名靠前的结果会在 7 月上映,因为 should
子句指定了对 7 月前后上映的电影的偏好。
对 movies
集合运行包含三个子句的 Atlas Search compound
查询。
创建一个名为
DateRangeComplex.java
的文件。将以下代码复制并粘贴到
DateRangeComplex.java
文件。此代码示例将执行以下任务:
导入
mongodb
包和依赖项。建立与您的 Atlas 集群的连接。
对上一个示例进行补充。
除了
must
和should
子句之外,此查询还包含一个mustNot
子句,用于指定结果中不得包含documentary
类型的电影。遍历游标以打印与查询匹配的文档。
1 import java.util.Arrays; 2 import java.util.List; 3 4 import static com.mongodb.client.model.Aggregates.limit; 5 import static com.mongodb.client.model.Aggregates.project; 6 import static com.mongodb.client.model.Projections.*; 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 import java.time.Instant; 14 import java.util.Date; 15 16 public class DateRangeComplex { 17 public static void main( String[] args ) { 18 // define clauses 19 List<Document> mustClauses = 20 List.of( new Document( 21 "range", new Document("path", "released") 22 .append("gt", Date.from(Instant.parse("2015-01-01T00:00:00.000Z"))) 23 .append("lt", Date.from(Instant.parse("2015-12-31T00:00:00.000Z"))))); 24 List<Document> shouldClauses = 25 List.of( 26 new Document( 27 "near", 28 new Document("pivot", 2629800000L) 29 .append("path", "released") 30 .append("origin", Date.from(Instant.parse("2015-07-01T00:00:00.000+00:00"))))); 31 List<Document> mustNotClauses = 32 List.of( 33 new Document( 34 "text", 35 new Document("query", "Documentary") 36 .append("path", "genres"))); 37 // define query 38 Document agg = 39 new Document( "$search", 40 new Document("index", "date-range-tutorial") 41 .append( "compound", 42 new Document().append("must", mustClauses) 43 .append("should", shouldClauses) 44 .append("mustNot", mustNotClauses))); 45 // specify connection 46 String uri = "<connection-string>"; 47 48 // establish connection and set namespace 49 try (MongoClient mongoClient = MongoClients.create(uri)) { 50 MongoDatabase database = mongoClient.getDatabase("sample_mflix"); 51 MongoCollection<Document> collection = database.getCollection("movies"); 52 53 // run query and print results 54 collection.aggregate(Arrays.asList(agg, 55 project(fields( 56 excludeId(), 57 include("title", "released", "genres"), 58 computed("score", new Document("$meta", "searchScore")))), 59 limit(6))) 60 .forEach(doc -> System.out.println(doc.toJson())); 61 } 62 } 63 } 注意
要在 Maven 环境中运行示例代码,请将以下代码添加到文件中的 import 语句上方。
package com.mongodb.drivers; 在运行示例之前,请将
<connection-string>
替换为 Atlas 连接字符串。确保您的连接字符串包含数据库用户的档案。要了解详情,请参阅通过驱动程序连接。编译并运行
DateRangeComplex.java
文件。javac DateRangeComplex.java java DateRangeComplex {"genres": ["Action", "Adventure", "Sci-Fi"], "title": "Terminator Genisys", "released": {"$date": "2015-07-01T00:00:00Z"}, "score": 2.0} {"genres": ["Comedy", "Drama", "Music"], "title": "Magic Mike XXL", "released": {"$date": "2015-07-01T00:00:00Z"}, "score": 2.0} {"genres": ["Comedy", "Drama"], "title": "Home Care", "released": {"$date": "2015-07-01T00:00:00Z"}, "score": 2.0} {"genres": ["Drama", "Mystery", "Sci-Fi"], "title": "Pig", "released": {"$date": "2015-07-02T00:00:00Z"}, "score": 1.9681909084320068} {"genres": ["Drama", "History", "Romance"], "title": "Gold Coast", "released": {"$date": "2015-07-02T00:00:00Z"}, "score": 1.9681909084320068} {"genres": ["Animation", "Family"], "title": "Zarafa", "released": {"$date": "2015-07-03T00:00:00Z"}, "score": 1.9383430480957031}
对于该查询,排名靠前的结果会在 7 月上映,因为 should
子句指定了对 7 月前后上映的电影的偏好。
对 movies
集合运行包含两个子句的 Atlas Search compound
查询。
创建一个名为
DateRange.kt
的文件。将以下代码复制并粘贴到
DateRange.kt
文件。此代码示例将执行以下任务:
导入
mongodb
包和依赖项。建立与您的 Atlas 集群的连接。
使用以下
compound
操作符子句对该集合进行查询:一个
must
子句,用于搜索在2015-01-01
和2015-12-31
之间上映的电影should
子句,用于指定优先选择在2012-07-01
附近上映的电影,中枢距离为 1 个月
该查询包括一个
$limit
阶段,将输出限制为 6 个结果,以及一个$project
阶段:排除
title
、released
和genres
字段以外的所有字段添加字段
score
打印与
AggregateFlow
实例中的查询相匹配的文档。
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.time.Instant 8 import java.util.* 9 10 fun main() { 11 // establish connection and set namespace 12 val uri = "<connection-string>" 13 val mongoClient = MongoClient.create(uri) 14 val database = mongoClient.getDatabase("sample_mflix") 15 val collection = database.getCollection<Document>("movies") 16 17 runBlocking { 18 // define clauses 19 val mustClauses = listOf( 20 Document( 21 "range", Document("path", "released") 22 .append("gt", Date.from(Instant.parse("2015-01-01T00:00:00.000Z"))) 23 .append("lt", Date.from(Instant.parse("2015-12-31T00:00:00.000Z"))) 24 ) 25 ) 26 27 val shouldClauses = listOf( 28 Document( 29 "near", 30 Document("pivot", 2629800000L) 31 .append("path", "released") 32 .append("origin", Date.from(Instant.parse("2015-07-01T00:00:00.000+00:00"))) 33 ) 34 ) 35 36 // define query 37 val agg = Document( 38 "\$search", 39 Document("index", "date-range-tutorial") 40 .append( 41 "compound", 42 Document().append("must", mustClauses) 43 .append("should", shouldClauses) 44 ) 45 ) 46 47 // run query and print results 48 val resultsFlow = collection.aggregate<Document>( 49 listOf( 50 agg, 51 limit(6), 52 project(fields( 53 excludeId(), 54 include("title", "released", "genres"), 55 computed("score", Document("\$meta", "searchScore")) 56 )) 57 ) 58 ) 59 resultsFlow.collect { println(it) } 60 } 61 mongoClient.close() 62 } 在运行示例之前,请将
<connection-string>
替换为 Atlas 连接字符串。确保您的连接字符串包含数据库用户的档案。要了解详情,请参阅通过驱动程序连接。运行
DateRange.kt
文件。当你在 IDE 中运行
DateRange.kt
程序时,它会打印以下文档:Document{{genres=[Action, Adventure, Sci-Fi], title=Terminator Genisys, released=Tue Jun 30 20:00:00 EDT 2015, score=2.0}} Document{{genres=[Comedy, Drama, Music], title=Magic Mike XXL, released=Tue Jun 30 20:00:00 EDT 2015, score=2.0}} Document{{genres=[Documentary, News], title=Bitcoin: The End of Money as We Know It, released=Tue Jun 30 20:00:00 EDT 2015, score=2.0}} Document{{genres=[Documentary, Biography, Drama], title=Mala Mala, released=Tue Jun 30 20:00:00 EDT 2015, score=2.0}} Document{{genres=[Comedy, Drama], title=Home Care, released=Tue Jun 30 20:00:00 EDT 2015, score=2.0}} Document{{genres=[Drama, Mystery, Sci-Fi], title=Pig, released=Wed Jul 01 20:00:00 EDT 2015, score=1.9681909084320068}}
对于该查询,排名靠前的结果会在 7 月上映,因为 should
子句指定了对 7 月前后上映的电影的偏好。
对 movies
集合运行包含三个子句的 Atlas Search compound
查询。
创建一个名为
DateRangeComplex.kt
的文件。将以下代码复制并粘贴到
DateRangeComplex.kt
文件。此代码示例将执行以下任务:
导入
mongodb
包和依赖项。建立与您的 Atlas 集群的连接。
对上一个示例进行补充。
除了
must
和should
子句之外,此查询还包含一个mustNot
子句,用于指定结果中不得包含documentary
类型的电影。打印与
AggregateFlow
实例中的查询相匹配的文档。
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.time.Instant 8 import java.util.* 9 10 fun main() { 11 // establish connection and set namespace 12 val uri = "<connection-string>" 13 val mongoClient = MongoClient.create(uri) 14 val database = mongoClient.getDatabase("sample_mflix") 15 val collection = database.getCollection<Document>("movies") 16 17 runBlocking { 18 // define clauses 19 val mustClauses = listOf( 20 Document( 21 "range", Document("path", "released") 22 .append("gt", Date.from(Instant.parse("2015-01-01T00:00:00.000Z"))) 23 .append("lt", Date.from(Instant.parse("2015-12-31T00:00:00.000Z"))) 24 ) 25 ) 26 27 val shouldClauses = listOf( 28 Document( 29 "near", 30 Document("pivot", 2629800000L) 31 .append("path", "released") 32 .append("origin", Date.from(Instant.parse("2015-07-01T00:00:00.000+00:00"))) 33 ) 34 ) 35 36 val mustNotClauses = listOf( 37 Document( 38 "text", 39 Document("query", "Documentary") 40 .append("path", "genres") 41 ) 42 ) 43 44 // define query 45 val agg = Document( 46 "\$search", 47 Document("index", "date-range-tutorial") 48 .append( 49 "compound", 50 Document().append("must", mustClauses) 51 .append("should", shouldClauses) 52 .append("mustNot", mustNotClauses) 53 ) 54 ) 55 56 // run query and print results 57 val resultsFlow = collection.aggregate<Document>( 58 listOf( 59 agg, 60 limit(6), 61 project(fields( 62 excludeId(), 63 include("title", "released", "genres"), 64 computed("score", Document("\$meta", "searchScore")) 65 )) 66 ) 67 ) 68 resultsFlow.collect { println(it) } 69 } 70 mongoClient.close() 71 } 在运行示例之前,请将
<connection-string>
替换为 Atlas 连接字符串。确保您的连接字符串包含数据库用户的档案。要了解详情,请参阅通过驱动程序连接。运行
DateRangeComplex.kt
文件。当你在 IDE 中运行
DateRangeComplex.kt
程序时,它会打印以下文档:Document{{genres=[Action, Adventure, Sci-Fi], title=Terminator Genisys, released=Tue Jun 30 20:00:00 EDT 2015, score=2.0}} Document{{genres=[Comedy, Drama, Music], title=Magic Mike XXL, released=Tue Jun 30 20:00:00 EDT 2015, score=2.0}} Document{{genres=[Comedy, Drama], title=Home Care, released=Tue Jun 30 20:00:00 EDT 2015, score=2.0}} Document{{genres=[Drama, Mystery, Sci-Fi], title=Pig, released=Wed Jul 01 20:00:00 EDT 2015, score=1.9681909084320068}} Document{{genres=[Drama, History, Romance], title=Gold Coast, released=Wed Jul 01 20:00:00 EDT 2015, score=1.9681909084320068}} Document{{genres=[Drama], title=Jackie & Ryan, released=Thu Jul 02 20:00:00 EDT 2015, score=1.9383430480957031}}
对于该查询,排名靠前的结果会在 7 月上映,因为 should
子句指定了对 7 月前后上映的电影的偏好。
对 movies
集合运行包含两个子句的 Atlas Search compound
查询。
创建一个名为
date-range.js
的文件。将以下代码复制并粘贴到
date-range.js
文件。此代码示例将执行以下任务:
导入
mongodb
,即 MongoDB 的 Node.js 驱动程序。创建一个
MongoClient
类实例,以建立与 Atlas 集群的连接。使用以下
compound
操作符子句对该集合进行查询:一个
must
子句,用于搜索在2015-01-01
和2015-12-31
之间上映的电影should
子句,用于指定优先选择在2012-07-01
附近上映的电影,中枢距离为 1 个月
该查询包括一个
$limit
阶段,将输出限制为 6 个结果,以及一个$project
阶段:排除
title
、released
和genres
字段以外的所有字段添加字段
score
遍历游标以打印与查询匹配的文档。
1 const { MongoClient } = require("mongodb"); 2 3 // connect to your Atlas cluster 4 const uri = 5 "<connection-string>"; 6 7 const client = new MongoClient(uri); 8 9 async function run() { 10 try { 11 await client.connect(); 12 13 // set namespace 14 const database = client.db("sample_mflix"); 15 const coll = database.collection("movies"); 16 17 // define pipeline 18 const agg = [ 19 { $search: { 20 index: 'date-range-tutorial', 21 compound: { 22 must: [{ range: { path: "released", gt: new Date("2015-01-01T00:00:00.000Z"), lt: new Date("2015-12-31T00:00:00.000Z") }}], 23 should: [{ near: { path: "released", origin: new Date("2015-07-01T00:00:00.000Z"), pivot: 2629800000 }}]}}}, 24 { $project: {_id: 0, title: 1, released: 1, genres: 1, score: { $meta: "searchScore" }}}, 25 { $limit: 6 } 26 ]; 27 28 // run pipeline 29 const result = await coll.aggregate(agg); 30 31 // print results 32 await result.forEach((doc) => console.log(doc)); 33 } finally { 34 await client.close(); 35 } 36 } 37 run().catch(console.dir); 在运行示例之前,请将
<connection-string>
替换为 Atlas 连接字符串。确保您的连接字符串包含数据库用户的档案。要了解详情,请参阅通过驱动程序连接。运行以下命令来查询您的集合:
node date-range.js { genres: [ 'Action', 'Adventure', 'Sci-Fi' ], title: 'Terminator Genisys', released: 2015-07-01T00:00:00.000Z, score: 2 } { genres: [ 'Comedy', 'Drama', 'Music' ], title: 'Magic Mike XXL', released: 2015-07-01T00:00:00.000Z, score: 2 } { genres: [ 'Documentary', 'Biography', 'Drama' ], title: 'Mala Mala', released: 2015-07-01T00:00:00.000Z, score: 2 } { genres: [ 'Comedy', 'Drama' ], title: 'Home Care', released: 2015-07-01T00:00:00.000Z, score: 2 } { genres: [ 'Documentary', 'News' ], title: 'Bitcoin: The End of Money as We Know It', released: 2015-07-01T00:00:00.000Z, score: 2 } { genres: [ 'Drama', 'Mystery', 'Sci-Fi' ], title: 'Pig', released: 2015-07-02T00:00:00.000Z, score: 1.9681909084320068 }
对于该查询,排名靠前的结果会在 7 月上映,因为 should
子句指定了对 7 月前后上映的电影的偏好。
对 movies
集合运行包含三个子句的 Atlas Search compound
查询。
创建一个名为
date-range-complex.js
的文件。将以下代码复制并粘贴到
date-range-complex.js
文件。此代码示例将执行以下任务:
导入
mongodb
,即 MongoDB 的 Node.js 驱动程序。创建一个
MongoClient
类实例,以建立与 Atlas 集群的连接。对上一个示例进行补充。
除了
must
和should
子句之外,此查询还包含一个mustNot
子句,用于指定结果中不得包含documentary
类型的电影。遍历游标以打印与查询匹配的文档。
1 const { MongoClient } = require("mongodb"); 2 3 // connect to your Atlas cluster 4 const uri = 5 "<connection-string>"; 6 7 const client = new MongoClient(uri); 8 9 async function run() { 10 try { 11 await client.connect(); 12 13 // set namespace 14 const database = client.db("sample_mflix"); 15 const coll = database.collection("movies"); 16 17 // define pipeline 18 const agg = [ 19 { $search: { 20 index: 'date-range-tutorial', 21 compound: { 22 must: [{ range: { path: "released", gt: new Date("2015-01-01T00:00:00.000Z"), lt: new Date("2015-12-31T00:00:00.000Z") }}], 23 should: [{ near: { path: "released", origin: new Date("2015-07-01T00:00:00.000Z"), pivot: 2629800000 }}], 24 mustNot: [{ text: { path: "genres", query: "Documentary"} }]}}}, 25 { $project: {_id: 0, title: 1, released: 1, genres: 1, score: { $meta: "searchScore" }}}, 26 { $limit: 6 } 27 ]; 28 29 // run pipeline 30 const result = await coll.aggregate(agg); 31 32 // print results 33 await result.forEach((doc) => console.log(doc)); 34 } finally { 35 await client.close(); 36 } 37 } 38 run().catch(console.dir); 在运行示例之前,请将
<connection-string>
替换为 Atlas 连接字符串。确保您的连接字符串包含数据库用户的档案。要了解详情,请参阅通过驱动程序连接。运行以下命令来查询您的集合:
node date-range-complex.js { genres: [ 'Action', 'Adventure', 'Sci-Fi' ], title: 'Terminator Genisys', released: 2015-07-01T00:00:00.000Z, score: 2 } { genres: [ 'Comedy', 'Drama', 'Music' ], title: 'Magic Mike XXL', released: 2015-07-01T00:00:00.000Z, score: 2 } { genres: [ 'Comedy', 'Drama' ], title: 'Home Care', released: 2015-07-01T00:00:00.000Z, score: 2 } { genres: [ 'Drama', 'Mystery', 'Sci-Fi' ], title: 'Pig', released: 2015-07-02T00:00:00.000Z, score: 1.9681909084320068 } { genres: [ 'Drama', 'History', 'Romance' ], title: 'Gold Coast', released: 2015-07-02T00:00:00.000Z, score: 1.9681909084320068 } { genres: [ 'Animation', 'Family' ], title: 'Zarafa', released: 2015-07-03T00:00:00.000Z, score: 1.9383430480957031 }
对于该查询,排名靠前的结果会在 7 月上映,因为 should
子句指定了对 7 月前后上映的电影的偏好。
对 movies
集合运行包含两个子句的 Atlas Search compound
查询。
创建一个名为
date-range.py
的文件。将以下代码复制并粘贴到
date-range.py
文件。以下代码示例:
导入
pymongo
、MongoDB 的 Python 驱动程序和dns
模块,这是使用 DNS 种子列表连接字符串将pymongo
连接到Atlas
所必需的。创建一个
MongoClient
类实例,以建立与 Atlas 集群的连接。使用以下
compound
操作符子句对该集合进行查询:一个
must
子句,用于搜索在2015-01-01
和2015-12-31
之间上映的电影should
子句,用于指定优先选择在2012-07-01
附近上映的电影,中枢距离为 1 个月
该查询包括一个
$limit
阶段,将输出限制为 6 个结果,以及一个$project
阶段:排除
title
、released
和genres
字段以外的所有字段添加字段
score
遍历游标以打印与查询匹配的文档。
1 import pymongo 2 import datetime 3 4 # connect to your Atlas cluster 5 client = pymongo.MongoClient("<connection-string>") 6 7 # define pipeline 8 pipeline = [ 9 {"$search": { 10 "index": "date-range-tutorial", 11 "compound": { 12 "must": [{"range": {"path": "released", "gt": datetime.datetime(2015,1,1,0,0,0), "lt": datetime.datetime(2015,12,31,0,0,0)}}], 13 "should": [{"near": {"path": "released", "origin": datetime.datetime(2015, 7, 1, 0, 0, 0, 0), "pivot": 2629800000}}]}}}, 14 {"$limit": 6}, 15 {"$project": {"_id": 0, "title": 1, "released": 1, "genres": 1, "score": {"$meta": "searchScore"}}} 16 ] 17 # run pipeline 18 result = client["sample_mflix"]["movies"].aggregate(pipeline) 19 20 # print results 21 for i in result: 22 print(i) 在运行示例之前,请将
<connection-string>
替换为 Atlas 连接字符串。确保您的连接字符串包含数据库用户的档案。要了解详情,请参阅通过驱动程序连接。运行以下命令来查询您的集合:
python date-range.py {'genres': ['Action', 'Adventure', 'Sci-Fi'], 'title': 'Terminator Genisys', 'released': datetime.datetime(2015, 7, 1, 0, 0), 'score': 2.0} {'genres': ['Comedy', 'Drama', 'Music'], 'title': 'Magic Mike XXL', 'released': datetime.datetime(2015, 7, 1, 0, 0), 'score': 2.0} {'genres': ['Documentary', 'Biography', 'Drama'], 'title': 'Mala Mala', 'released': datetime.datetime(2015, 7, 1, 0, 0), 'score': 2.0} {'genres': ['Comedy', 'Drama'], 'title': 'Home Care', 'released': datetime.datetime(2015, 7, 1, 0, 0), 'score': 2.0} {'genres': ['Documentary', 'News'], 'title': 'Bitcoin: The End of Money as We Know It', 'released': datetime.datetime(2015, 7, 1, 0, 0), 'score': 2.0} {'genres': ['Drama', 'Mystery', 'Sci-Fi'], 'title': 'Pig', 'released': datetime.datetime(2015, 7, 2, 0, 0), 'score': 1.9681909084320068}
对于该查询,排名靠前的结果会在 7 月上映,因为 should
子句指定了对 7 月前后上映的电影的偏好。
对 movies
集合运行包含三个子句的 Atlas Search compound
查询。
创建一个名为
date-range-complex.py
的文件。将以下代码复制并粘贴到
date-range-complex.py
文件。以下代码示例:
导入
pymongo
、MongoDB 的 Python 驱动程序和dns
模块,这是使用 DNS 种子列表连接字符串将pymongo
连接到Atlas
所必需的。创建一个
MongoClient
类实例,以建立与 Atlas 集群的连接。对上一个示例进行补充。
除了
must
和should
子句之外,此查询还包含一个mustNot
子句,用于指定结果中不得包含documentary
类型的电影。遍历游标以打印与查询匹配的文档。
1 import pymongo 2 import datetime 3 4 # connect to your Atlas cluster 5 client = pymongo.MongoClient("<connection-string>") 6 7 # define pipeline 8 pipeline = [ 9 {"$search": { 10 "index": "date-range-tutorial", 11 "compound": { 12 "must": [{"range": {"path": "released", "gt": datetime.datetime(2015,1,1,0,0,0), "lt": datetime.datetime(2015,12,31,0,0,0)}}], 13 "should": [{"near": {"path": "released", "origin": datetime.datetime(2015, 7, 1, 0, 0, 0, 0), "pivot": 2629800000}}], 14 "mustNot": [{"text": {"path": "genres", "query": "Documentary"}}]}}}, 15 {"$limit": 6}, 16 {"$project": {"_id": 0, "title": 1, "released": 1, "genres": 1, "score": {"$meta": "searchScore"}}} 17 ] 18 # run pipeline 19 result = client["sample_mflix"]["movies"].aggregate(pipeline) 20 21 # print results 22 for i in result: 23 print(i) 在运行示例之前,请将
<connection-string>
替换为 Atlas 连接字符串。确保您的连接字符串包含数据库用户的档案。要了解详情,请参阅通过驱动程序连接。运行以下命令来查询您的集合:
python date-range-complex.py {'genres': ['Action', 'Adventure', 'Sci-Fi'], 'title': 'Terminator Genisys', 'released': datetime.datetime(2015, 7, 1, 0, 0), 'score': 2.0} {'genres': ['Comedy', 'Drama', 'Music'], 'title': 'Magic Mike XXL', 'released': datetime.datetime(2015, 7, 1, 0, 0), 'score': 2.0} {'genres': ['Comedy', 'Drama'], 'title': 'Home Care', 'released': datetime.datetime(2015, 7, 1, 0, 0), 'score': 2.0} {'genres': ['Drama', 'Mystery', 'Sci-Fi'], 'title': 'Pig', 'released': datetime.datetime(2015, 7, 2, 0, 0), 'score': 1.9681909084320068} {'genres': ['Drama', 'History', 'Romance'], 'title': 'Gold Coast', 'released': datetime.datetime(2015, 7, 2, 0, 0), 'score': 1.9681909084320068} {'genres': ['Animation', 'Family'], 'title': 'Zarafa', 'released': datetime.datetime(2015, 7, 3, 0, 0), 'score': 1.9383430480957031}
对于该查询,排名靠前的结果会在 7 月上映,因为 should
子句指定了对 7 月前后上映的电影的偏好。