Docs 菜单
Docs 主页
/
MongoDB Atlas
/ /

如何使用日期范围筛选器运行 Atlas Search 查询

在此页面上

  • 使用动态映射创建 Atlas Search 索引
  • 运行复合查询

本教程介绍如何在 sample_mflix.movies集合上创建具有动态映射的索引。它展示了如何使用 范围接近操作符对 released 字段运行复合查询。它将引导您完成以下步骤:

  1. sample_mflix.movies集合设置具有动态映射的 Atlas Search 索引。

  2. 针对 sample_mflix.movies 集合中的 released 字段运行 Atlas Search 复合查询。

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

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

在本部分中,我们将创建一个 Atlas Search 索引,该索引使用动态映射sample_mflix.movies集合的字段编制索引。

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

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

  3. 如果尚未出现,请单击侧边栏中的 Clusters(部署)。

    显示 集群页面。

2

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

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

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

    将显示 Atlas Search 页面。

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

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

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

    将显示 Atlas Search 页面。

  1. 单击集群的名称。

  2. 单击 Atlas Search 标签页。

    将显示 Atlas Search 页面。

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

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

5
  1. Index Name 字段中输入 date-range-tutorial

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

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

6

您可以创建使用动态映射静态映射的 Atlas Search 索引。要了解有关动态和静态映射的更多信息,请参阅静态和动态映射

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

  1. 单击 Next(连接)。

  2. 查看 movies 集合的 "date-range-tutorial" 索引定义。

  1. 单击 Next(连接)。

  2. 查看索引定义。

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

    {
    "mappings": {
    "dynamic": true
    }
    }

    上述索引定义对 movies 集合中每个文档中的支持类型字段动态创建索引。

  3. 单击 Next(连接)。

7
8
9

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

10

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


➤ 使用 Select your language(选择您的语言)下拉菜单设置此页面上示例的语言。


您可以使用复合运算符将两个或多个运算符和子句组合成一个查询。本教程使用复合运算符子句搜索指定日期范围内的电影。在本部分中,连接到您的 Atlas 集群并使用复合运算符对 sample_mflix.movies 中的 released 字段运行示例查询。

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

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

  3. 如果尚未出现,请单击侧边栏中的 Clusters(部署)。

    会显示集群页面。

2

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

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

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

    将显示 Atlas Search 页面。

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

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

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

    将显示 Atlas Search 页面。

  1. 单击集群的名称。

  2. 单击 Atlas Search 标签页。

    将显示 Atlas Search 页面。

3

单击要查询的索引右侧的 Query 按钮。

4

单击Edit Query查看 JSON格式的默认查询语法示例。

5

以下示例使用带有子查询的 compound 操作符来搜索 20102015 年之间的电影。该查询使用以下子句:

  • 一个 must 子句,用于搜索在 2015-01-012015-12-31 之间上映的电影

  • should 子句,用于指定优先选择在 2012-07-01 附近上映的电影,中枢距离为 1 个月

该查询包括一个 $limit 阶段,将输出限制为 6 个结果,以及一个 $project 阶段:

  • 排除 titlereleasedgenres 字段以外的所有字段

  • 添加字段 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
...
6

Search Tester 可能不会显示其所返回文档的所有字段。要查看所有字段,包括在查询路径中指定的字段,请展开结果中的文档。

对于该查询,排名靠前的结果会在 7 月上映,因为 should 子句指定了对 7 月前后上映的电影的偏好。

7

以下示例是对上一个示例的补充。

除了 mustshould 子句之外,此查询还包含一个 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
...
8

Search Tester 可能不会显示其所返回文档的所有字段。要查看所有字段,包括在查询路径中指定的字段,请展开结果中的文档。

对于该查询,排名靠前的结果会在 7 月上映,因为 should 子句指定了对 7 月前后上映的电影的偏好。

1

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

2

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

use sample_mflix
3

以下示例使用带有子查询的 compound 操作符来搜索 20102015 年之间的电影。该查询使用以下子句:

  • 一个 must 子句,用于搜索在 2015-01-012015-12-31 之间上映的电影

  • should 子句,用于指定优先选择在 2012-07-01 附近上映的电影,中枢距离为 1 个月

该查询包括一个 $limit 阶段,将输出限制为 6 个结果,以及一个 $project 阶段:

  • 排除 titlereleasedgenres 字段以外的所有字段

  • 添加字段 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 月前后上映的电影的偏好。

4

以下示例是对上一个示例的补充。

除了 mustshould 子句之外,此查询还包含一个 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 月前后上映的电影的偏好。

1

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

2

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

3

以下示例使用带有子查询的 compound 操作符来搜索 20102015 年之间的电影。该查询使用以下子句:

  • 一个 must 子句,用于搜索在 2015-01-012015-12-31 之间上映的电影

  • should 子句,用于指定优先选择在 2012-07-01 附近上映的电影,中枢距离为 1 个月

该查询包括一个 $limit 阶段,将输出限制为 6 个结果,以及一个 $project 阶段:

  • 排除 titlereleasedgenres 字段以外的所有字段

  • 添加字段 score

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

  1. 单击 Aggregations 标签页。

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

管道阶段
查询
$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"
}
}

如果启用了 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 月前后上映的电影的偏好。

4

以下示例是对上一个示例的补充。

除了 mustshould 子句之外,此查询还包含一个 mustNot 子句,用于指定结果中不得包含 documentary 类型的电影。

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

  1. 单击 Aggregations 标签页。

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

管道阶段
查询
$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
}
}],
"mustNot": [{
"text": {
"query": "documentary",
"path": "genres"
}
}]
}
}
$limit
6
$project
{
"_id": 0,
"title": 1,
"released": 1,
"genres": 1,
"score": {
"$meta": "searchScore"
}
}

如果启用了 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 月前后上映的电影的偏好。

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

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

    dotnet add package MongoDB.Driver
2
  1. Program.cs文件的内容替换为以下代码。

    此代码示例将执行以下任务:

    • 导入mongodb包和依赖项。

    • 建立与您的 Atlas 集群的连接。

    • 使用以下 compound 操作符子句对该集合进行查询:

      • 一个 must 子句,用于搜索在 2015-01-012015-12-31 之间上映的电影

      • should 子句,用于指定优先选择在 2012-07-01 附近上映的电影,中枢距离为 1 个月

      该查询包括一个 $limit 阶段,将输出限制为 6 个结果,以及一个 $project 阶段:

      • 排除 titlereleasedgenres 字段以外的所有字段

      • 添加字段 score

    • 遍历游标以打印与查询匹配的文档。

    1using MongoDB.Bson;
    2using MongoDB.Bson.Serialization.Attributes;
    3using MongoDB.Bson.Serialization.Conventions;
    4using MongoDB.Driver;
    5using MongoDB.Driver.Search;
    6
    7public 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[BsonIgnoreExtraElements]
    51public class MovieDocument
    52{
    53 [BsonIgnoreIfDefault]
    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}
  2. 在运行示例之前,请将 <connection-string> 替换为 Atlas 连接字符串。确保您的连接字符串包含数据库用户的档案。要了解详情,请参阅通过驱动程序连接。

  3. 编译并运行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 月前后上映的电影的偏好。

3
  1. Program.cs文件的内容替换为以下代码。

    此代码示例将执行以下任务:

    • 导入mongodb包和依赖项。

    • 建立与您的 Atlas 集群的连接。

    • 对上一个示例进行补充。

      除了 mustshould 子句之外,此查询还包含一个 mustNot 子句,用于指定结果中不得包含 documentary 类型的电影。

    • 遍历游标以打印与查询匹配的文档。

    1using MongoDB.Bson;
    2using MongoDB.Bson.Serialization.Attributes;
    3using MongoDB.Bson.Serialization.Conventions;
    4using MongoDB.Driver;
    5using MongoDB.Driver.Search;
    6
    7public 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[BsonIgnoreExtraElements]
    52public class MovieDocument
    53{
    54 [BsonIgnoreIfDefault]
    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}
  2. 在运行示例之前,请将 <connection-string> 替换为 Atlas 连接字符串。确保您的连接字符串包含数据库用户的档案。要了解详情,请参阅通过驱动程序连接。

  3. 编译并运行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 月前后上映的电影的偏好。

1
  1. 创建一个名为 date-range.go 的文件。

  2. 将以下代码复制并粘贴到 date-range.go 文件。

    此代码示例将执行以下任务:

    • 导入mongodb包和依赖项。

    • 建立与您的 Atlas 集群的连接。

    • 使用以下 compound 操作符子句对该集合进行查询:

      • 一个 must 子句,用于搜索在 2015-01-012015-12-31 之间上映的电影

      • should 子句,用于指定优先选择在 2012-07-01 附近上映的电影,中枢距离为 1 个月

      该查询包括一个 $limit 阶段,将输出限制为 6 个结果,以及一个 $project 阶段:

      • 排除 titlereleasedgenres 字段以外的所有字段

      • 添加字段 score

    • 遍历游标以打印与查询匹配的文档。

    1package main
    2
    3import (
    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
    13func 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}
  3. 在运行示例之前,请将 <connection-string> 替换为 Atlas 连接字符串。确保您的连接字符串包含数据库用户的档案。要了解详情,请参阅通过驱动程序连接。

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

    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 月前后上映的电影的偏好。

2
  1. 创建一个名为 date-range-complex.go 的文件。

  2. 将以下代码复制并粘贴到 date-range-complex.go 文件。

    此代码示例将执行以下任务:

    • 导入mongodb包和依赖项。

    • 建立与您的 Atlas 集群的连接。

    • 对上一个示例进行补充。

      除了 mustshould 子句之外,此查询还包含一个 mustNot 子句,用于指定结果中不得包含 documentary 类型的电影。

    • 遍历游标以打印与查询匹配的文档。

    1package main
    2
    3import (
    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
    13func 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}
  3. 在运行示例之前,请将 <connection-string> 替换为 Atlas 连接字符串。确保您的连接字符串包含数据库用户的档案。要了解详情,请参阅通过驱动程序连接。

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

    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 月前后上映的电影的偏好。

1
junit
4.11 或更高版本
mongodb-driver-sync
4.3.0 或更高版本
slf4j-log4j12
1.7.30 或更高版本
2
  1. 创建一个名为 DateRange.java 的文件。

  2. 将以下代码复制并粘贴到 DateRange.java 文件。

    此代码示例将执行以下任务:

    • 导入mongodb包和依赖项。

    • 建立与您的 Atlas 集群的连接。

    • 使用以下 compound 操作符子句对该集合进行查询:

      • 一个 must 子句,用于搜索在 2015-01-012015-12-31 之间上映的电影

      • should 子句,用于指定优先选择在 2012-07-01 附近上映的电影,中枢距离为 1 个月

      该查询包括一个 $limit 阶段,将输出限制为 6 个结果,以及一个 $project 阶段:

      • 排除 titlereleasedgenres 字段以外的所有字段

      • 添加字段 score

    • 遍历游标以打印与查询匹配的文档。

    1import java.util.Arrays;
    2import java.util.List;
    3
    4import static com.mongodb.client.model.Aggregates.limit;
    5import static com.mongodb.client.model.Aggregates.project;
    6import static com.mongodb.client.model.Projections.*;
    7import com.mongodb.client.MongoClient;
    8import com.mongodb.client.MongoClients;
    9import com.mongodb.client.MongoCollection;
    10import com.mongodb.client.MongoDatabase;
    11import org.bson.Document;
    12
    13import java.time.Instant;
    14import java.util.Date;
    15
    16public 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;
  3. 在运行示例之前,请将 <connection-string> 替换为 Atlas 连接字符串。确保您的连接字符串包含数据库用户的档案。要了解详情,请参阅通过驱动程序连接。

  4. 编译并运行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 月前后上映的电影的偏好。

3
  1. 创建一个名为 DateRangeComplex.java 的文件。

  2. 将以下代码复制并粘贴到 DateRangeComplex.java 文件。

    此代码示例将执行以下任务:

    • 导入mongodb包和依赖项。

    • 建立与您的 Atlas 集群的连接。

    • 对上一个示例进行补充。

      除了 mustshould 子句之外,此查询还包含一个 mustNot 子句,用于指定结果中不得包含 documentary 类型的电影。

    • 遍历游标以打印与查询匹配的文档。

    1import java.util.Arrays;
    2import java.util.List;
    3
    4import static com.mongodb.client.model.Aggregates.limit;
    5import static com.mongodb.client.model.Aggregates.project;
    6import static com.mongodb.client.model.Projections.*;
    7import com.mongodb.client.MongoClient;
    8import com.mongodb.client.MongoClients;
    9import com.mongodb.client.MongoCollection;
    10import com.mongodb.client.MongoDatabase;
    11import org.bson.Document;
    12
    13import java.time.Instant;
    14import java.util.Date;
    15
    16public 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;
  3. 在运行示例之前,请将 <connection-string> 替换为 Atlas 连接字符串。确保您的连接字符串包含数据库用户的档案。要了解详情,请参阅通过驱动程序连接。

  4. 编译并运行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 月前后上映的电影的偏好。

1
mongodb-driver-kotlin-coroutine
4.10.0 或更高版本
2
  1. 创建一个名为 DateRange.kt 的文件。

  2. 将以下代码复制并粘贴到 DateRange.kt 文件。

    此代码示例将执行以下任务:

    • 导入mongodb包和依赖项。

    • 建立与您的 Atlas 集群的连接。

    • 使用以下 compound 操作符子句对该集合进行查询:

      • 一个 must 子句,用于搜索在 2015-01-012015-12-31 之间上映的电影

      • should 子句,用于指定优先选择在 2012-07-01 附近上映的电影,中枢距离为 1 个月

      该查询包括一个 $limit 阶段,将输出限制为 6 个结果,以及一个 $project 阶段:

      • 排除 titlereleasedgenres 字段以外的所有字段

      • 添加字段 score

    • 打印与 AggregateFlow 实例中的查询相匹配的文档。

    1import com.mongodb.client.model.Aggregates.limit
    2import com.mongodb.client.model.Aggregates.project
    3import com.mongodb.client.model.Projections.*
    4import com.mongodb.kotlin.client.coroutine.MongoClient
    5import kotlinx.coroutines.runBlocking
    6import org.bson.Document
    7import java.time.Instant
    8import java.util.*
    9
    10fun 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}
  3. 在运行示例之前,请将 <connection-string> 替换为 Atlas 连接字符串。确保您的连接字符串包含数据库用户的档案。要了解详情,请参阅通过驱动程序连接。

  4. 运行 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 月前后上映的电影的偏好。

3
  1. 创建一个名为 DateRangeComplex.kt 的文件。

  2. 将以下代码复制并粘贴到 DateRangeComplex.kt 文件。

    此代码示例将执行以下任务:

    • 导入mongodb包和依赖项。

    • 建立与您的 Atlas 集群的连接。

    • 对上一个示例进行补充。

      除了 mustshould 子句之外,此查询还包含一个 mustNot 子句,用于指定结果中不得包含 documentary 类型的电影。

    • 打印与 AggregateFlow 实例中的查询相匹配的文档。

    1import com.mongodb.client.model.Aggregates.limit
    2import com.mongodb.client.model.Aggregates.project
    3import com.mongodb.client.model.Projections.*
    4import com.mongodb.kotlin.client.coroutine.MongoClient
    5import kotlinx.coroutines.runBlocking
    6import org.bson.Document
    7import java.time.Instant
    8import java.util.*
    9
    10fun 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}
  3. 在运行示例之前,请将 <connection-string> 替换为 Atlas 连接字符串。确保您的连接字符串包含数据库用户的档案。要了解详情,请参阅通过驱动程序连接。

  4. 运行 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 月前后上映的电影的偏好。

1
  1. 创建一个名为 date-range.js 的文件。

  2. 将以下代码复制并粘贴到 date-range.js 文件。

    此代码示例将执行以下任务:

    • 导入 mongodb,即 MongoDB 的 Node.js 驱动程序。

    • 创建一个 MongoClient 类实例,以建立与 Atlas 集群的连接。

    • 使用以下 compound 操作符子句对该集合进行查询:

      • 一个 must 子句,用于搜索在 2015-01-012015-12-31 之间上映的电影

      • should 子句,用于指定优先选择在 2012-07-01 附近上映的电影,中枢距离为 1 个月

      该查询包括一个 $limit 阶段,将输出限制为 6 个结果,以及一个 $project 阶段:

      • 排除 titlereleasedgenres 字段以外的所有字段

      • 添加字段 score

    • 遍历游标以打印与查询匹配的文档。

    1const { MongoClient } = require("mongodb");
    2
    3// connect to your Atlas cluster
    4const uri =
    5 "<connection-string>";
    6
    7const client = new MongoClient(uri);
    8
    9async 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}
    37run().catch(console.dir);
  3. 在运行示例之前,请将 <connection-string> 替换为 Atlas 连接字符串。确保您的连接字符串包含数据库用户的档案。要了解详情,请参阅通过驱动程序连接。

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

    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 月前后上映的电影的偏好。

2
  1. 创建一个名为 date-range-complex.js 的文件。

  2. 将以下代码复制并粘贴到 date-range-complex.js 文件。

    此代码示例将执行以下任务:

    • 导入 mongodb,即 MongoDB 的 Node.js 驱动程序。

    • 创建一个 MongoClient 类实例,以建立与 Atlas 集群的连接。

    • 对上一个示例进行补充。

      除了 mustshould 子句之外,此查询还包含一个 mustNot 子句,用于指定结果中不得包含 documentary 类型的电影。

    • 遍历游标以打印与查询匹配的文档。

    1const { MongoClient } = require("mongodb");
    2
    3// connect to your Atlas cluster
    4const uri =
    5 "<connection-string>";
    6
    7const client = new MongoClient(uri);
    8
    9async 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}
    38run().catch(console.dir);
  3. 在运行示例之前,请将 <connection-string> 替换为 Atlas 连接字符串。确保您的连接字符串包含数据库用户的档案。要了解详情,请参阅通过驱动程序连接。

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

    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 月前后上映的电影的偏好。

1
  1. 创建一个名为 date-range.py 的文件。

  2. 将以下代码复制并粘贴到 date-range.py 文件。

    以下代码示例:

    • 导入 pymongo 、MongoDB 的 Python 驱动程序和 dns 模块,这是使用 DNS 种子列表连接字符串将 pymongo 连接到 Atlas 所必需的。

    • 创建一个 MongoClient 类实例,以建立与 Atlas 集群的连接。

    • 使用以下 compound 操作符子句对该集合进行查询:

      • 一个 must 子句,用于搜索在 2015-01-012015-12-31 之间上映的电影

      • should 子句,用于指定优先选择在 2012-07-01 附近上映的电影,中枢距离为 1 个月

      该查询包括一个 $limit 阶段,将输出限制为 6 个结果,以及一个 $project 阶段:

      • 排除 titlereleasedgenres 字段以外的所有字段

      • 添加字段 score

    • 遍历游标以打印与查询匹配的文档。

    1import pymongo
    2import datetime
    3
    4# connect to your Atlas cluster
    5client = pymongo.MongoClient("<connection-string>")
    6
    7# define pipeline
    8pipeline = [
    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
    18result = client["sample_mflix"]["movies"].aggregate(pipeline)
    19
    20# print results
    21for i in result:
    22 print(i)
  3. 在运行示例之前,请将 <connection-string> 替换为 Atlas 连接字符串。确保您的连接字符串包含数据库用户的档案。要了解详情,请参阅通过驱动程序连接。

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

    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 月前后上映的电影的偏好。

2
  1. 创建一个名为 date-range-complex.py 的文件。

  2. 将以下代码复制并粘贴到 date-range-complex.py 文件。

    以下代码示例:

    • 导入 pymongo 、MongoDB 的 Python 驱动程序和 dns 模块,这是使用 DNS 种子列表连接字符串将 pymongo 连接到 Atlas 所必需的。

    • 创建一个 MongoClient 类实例,以建立与 Atlas 集群的连接。

    • 对上一个示例进行补充。

      除了 mustshould 子句之外,此查询还包含一个 mustNot 子句,用于指定结果中不得包含 documentary 类型的电影。

    • 遍历游标以打印与查询匹配的文档。

    1import pymongo
    2import datetime
    3
    4# connect to your Atlas cluster
    5client = pymongo.MongoClient("<connection-string>")
    6
    7# define pipeline
    8pipeline = [
    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
    19result = client["sample_mflix"]["movies"].aggregate(pipeline)
    20
    21# print results
    22for i in result:
    23 print(i)
  3. 在运行示例之前,请将 <connection-string> 替换为 Atlas 连接字符串。确保您的连接字符串包含数据库用户的档案。要了解详情,请参阅通过驱动程序连接。

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

    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 月前后上映的电影的偏好。

后退

对象数组