如何对日期和数值字段运行 Atlas Search 字符串查询
本教程介绍如何针对 sample_airbnb.listingsAndReviews
集合中的 string
、date
和 number
字段运行 Atlas Search 查询。您将创建一个以字符串形式存储数字和日期字段值的 物化视图。然后,您将在物化视图上创建 Atlas Search 索引,并使用 queryString 和自动完成操作符针对这些 string 字段运行查询。本教程将指导您完成以下步骤:
在
sample_airbnb.listingsAndReviews
集合name
、property_type
、last_scraped
和accomodates
字段上创建物化视图。在物化视图上设置动态和静态 Atlas 搜索索引。
使用 queryString 和自动完成操作符对物化视图中的字段运行 Atlas Search 查询来搜索属性。
开始之前,请确保 Atlas 集群满足先决条件中所述的要求。
要创建 Atlas Search 索引,您必须拥有 Project Data Access Admin
或更高的项目访问权限。
在集合上创建物化视图
在本节中,您将为 airbnb_listingsAndReviews
集合中的 name
、property_type
、last_scraped
、accomodates
和 maximum_nights
字段创建名为 airbnb-mat-view
的物化视图。通过物化视图,可以将源集合中的数字和日期字段作为 string 字段存储在物化视图中。
登录到Atlas并使用mongosh
连接到集群。
在终端窗口中打开mongosh
并连接到集群。 有关连接的详细说明,请参阅通过mongosh
连接。
验证并切换到 sample_airbnb
数据库。
运行以下命令,验证集群中是否存在该数据库:
show dbs sample_airbnb 55.3 MB sample_analytics 9.59 MB sample_geospatial 1.43 MB sample_guides 41 kB sample_mflix 51.1 MB sample_restaurants 6.95 MB sample_supplies 1.21 MB sample_training 55.5 MB sample_weatherdata 2.89 MB admin 348 kB local 2.1 GB 运行以下命令以切换到
sample_airbnb
数据库。use sample_airbnb switched to db sample_airbnb
创建名为 airbnb_mat_view
的物化视图。
要创建物化视图,请运行以下查询。 该查询指定了以下聚合管道阶段:
$project
在此阶段,查询会执行以下操作:使用
$dateToString
将last_scraped
日期对象转换为YYYY-MM-DD
格式的string 。包括
name
和property_type
string 字段。使用 将
accomodates
数字字段转换为string$toString
。使用 将
maximum_nights
数字字段转换为string$toString
。
$merge
:在此阶段,查询会将$project
阶段的输出字段写入名为airbnb_mat_view
的物化视图。db.listingsAndReviews.aggregate( [ { $project: { lastScrapedDate: { $dateToString: { format: "%Y-%m-%d", date: "$last_scraped" } }, propertyName: "$name", propertyType: "$property_type", accommodatesNumber: { $toString: "$accommodates" }, maximumNumberOfNights: { $toString: "$maximum_nights" } } }, { $merge: { into: "airbnb_mat_view", whenMatched: "replace" } } ] )
在物化视图中的字段上创建 Atlas Search 索引
在本部分中,您将在lastScrapedDate
、 name
、 propertyType
、 accommodatesNumber
和maximumNumberOfNights
字段上创建 Atlas Search 索引,以便对这些字段运行查询。
AtlasGoClusters在Atlas中,Go项目的 页面。
如果尚未显示,请从导航栏上的 Organizations 菜单中选择包含所需项目的组织。
如果尚未显示,请从导航栏的Projects菜单中选择所需的项目。
如果尚未出现,请单击侧边栏中的 Clusters(部署)。
会显示集群页面。
转到集群的 Atlas Search 页面。
您可以从侧边栏、 Data Explorer 或集群详细信息页面转到 Atlas Search 页面。
在侧边栏中,单击 Services 标题下的 Atlas Search。
从 Select data source 下拉菜单中选择您的集群并单击 Go to Atlas Search。
将显示 Atlas Search 页面。
单击集群的对应 Browse Collections 按钮。
展开数据库并选择集合。
单击该集合的 Search Indexes 标签页。
将显示 Atlas Search 页面。
单击集群的名称。
单击 Atlas Search 标签页。
将显示 Atlas Search 页面。
输入 Index Name(索引名称),然后设置 Database and Collection(数据库和集合)。
在 Index Name 字段中输入
date-number-fields-tutorial
。如果将索引命名为
default
,则在使用 $search 管道阶段时无需指定index
参数。如果您为索引指定了自定义名称,则必须在index
参数中指定此名称。在 Database and Collection(数据库和集合)部分中找到
sample_airbnb
数据库,然后选择airbnb_mat_view
集合。
在物化视图的字段上定义索引。
您可以创建以下索引之一:
使用动态映射的索引,通过 queryString 操作符运行查询。如果索引定义只使用动态映射,则无法使用 autocomplete 操作符运行查询。
使用自动完成操作符运行查询时使用静态映射的索引。您无法使用 queryString 操作符对索引为类型
autocomplete
的字段运行查询。
您可以使用 Atlas 用户界面中的 Visual Editor 或 JSON Editor 来创建索引。
单击 Next(连接)。
单击 Create Search Index(连接)。
查看索引定义。
索引定义应类似于以下内容:
{ "mappings": { "dynamic": true } } 单击 Next(连接)。
单击 Create Search Index(连接)。
您可以使用 Atlas 用户界面中的 Visual Editor 或 JSON Editor 来创建索引。
单击 Next
单击 Refine Your Index(连接)。
单击 Field Mappings 部分中的 Add Field。
单击 Add Field Mapping(开始存档)窗口中的 Customized Configuration(确认)。
从 Field Name 下拉列表中选择 accommodatesNumber。
单击 Data Type 下拉菜单,从下拉菜单中选择 Autocomplete,然后配置以下字段:
用户界面字段名称配置Max Grams<maximum number of characters to index per sequence, numeric value>
Min Grams<minimum number of characters to index per sequence, numeric value.
TokenizationedgeGramFold Diacriticstrue极低的
Min Grams
值可能会导致索引极大。单击 Add 将字段添加到 Field Mappings 表中。
在 Field Mappings 部分单击 Add Field,并重复步骤 d 到步骤 f,配置以下字段的设置:
lastScrapedDate
numberOfNights
单击 Save Changes(连接)。
将默认索引定义替换为以下示例索引定义。
{ "mappings": { "dynamic": false, "fields": { "accommodatesNumber": [ { "dynamic": true, "type": "document" }, { "minGrams": 1, "type": "autocomplete" } ], "lastScrapedDate": [ { "dynamic": true, "type": "document" }, { "type": "autocomplete" } ], "maximumNumberOfNights": [ { "dynamic": true, "type": "document" }, { "minGrams": 1, "type": "autocomplete" } ] } } } 单击 Next(连接)。
对转换后的字段执行文本搜索
您可以对已转换为字符串的 numeric 和 date 字段运行查询。本教程使用 queryString 和 autocomplete 操作符来搜索属性。查询使用了下列管道阶段:
在本部分中,您将连接到 Atlas 集群,并使用运算符针对airbnb_mat_view
集合中的字段运行样本查询。
➤ 使用本页的“选择语言”下拉菜单设置本节示例的语言。
使用 mongosh
连接到集群。
在终端窗口中打开mongosh
并连接到集群。 有关连接的详细说明,请参阅通过mongosh
连接。
使用 sample_airbnb
数据库。
在 mongosh
提示符下运行以下命令:
use sample_airbnb
switched to db sample_airbnb
使用您为其创建索引的操作符运行以下 Atlas Search 搜索查询。
如果创建了使用动态映射的索引,您可以使用 queryString 操作符查询 airbnb_mat_view
集合。如果创建了使用静态映射的索引,您可以使用 autocomplete 操作符查询 airbnb_mat_view
集合。
以下查询搜索房产类型为 Apartment
或 Condominium
,可容纳 2
个人并在 2019
中列出的房产。
db.airbnb_mat_view.aggregate([ { "$search": { "index": "date-number-fields-tutorial", "queryString": { "defaultPath": "propertyType", "query": "propertyType: (Apartment OR Condominium) AND accommodatesNumber: 4 AND lastScrapedDate: 2019" } } }, { $limit: 5 }, { $project: { "_id": 0 } } ])
1 [ 2 { 3 lastScrapedDate: '2019-03-06', 4 propertyName: 'LAHAINA, MAUI! RESORT/CONDO BEACHFRONT!! SLEEPS 4!', 5 propertyType: 'Condominium', 6 accommodatesNumber: '4' 7 }, 8 { 9 lastScrapedDate: '2019-03-06', 10 propertyName: 'Makaha Valley Paradise with OceanView', 11 propertyType: 'Condominium', 12 accommodatesNumber: '4' 13 }, 14 { 15 lastScrapedDate: '2019-03-06', 16 propertyName: 'March 2019 availability! Oceanview on Sugar Beach!', 17 propertyType: 'Condominium', 18 accommodatesNumber: '4' 19 }, 20 { 21 lastScrapedDate: '2019-03-06', 22 propertyName: 'Tropical Jungle Oasis', 23 propertyType: 'Condominium', 24 accommodatesNumber: '4' 25 }, 26 { 27 lastScrapedDate: '2019-02-11', 28 propertyName: 'Hospede-se com acesso fácil.', 29 propertyType: 'Condominium', 30 accommodatesNumber: '4' 31 } 32 ] 33
以下查询搜索房产类型为House
、可容纳2
人、列在2019
中或最多允许住宿晚数30
晚的房产。
db.airbnb_mat_view.aggregate([ { "$search": { "index": "date-number-fields-tutorial", "queryString": { "defaultPath": "propertyType", "query": "propertyType: House OR accommodatesNumber: 2 OR lastScrapedDate: 2019 OR maximumNumberOfNights: 30" } } }, { $limit: 5 }, { $project: { "_id": 0 } } ])
1 [ 2 { 3 lastScrapedDate: '2019-02-11', 4 propertyName: '2017 , férias no Rio', 5 propertyType: 'House', 6 accommodatesNumber: '2', 7 maximumNumberOfNights: '30' 8 }, 9 { 10 lastScrapedDate: '2019-03-07', 11 propertyName: 'Newly renovated home', 12 propertyType: 'House', 13 accommodatesNumber: '2', 14 maximumNumberOfNights: '30' 15 }, 16 { 17 lastScrapedDate: '2019-02-18', 18 propertyName: 'Vintage House For Rent', 19 propertyType: 'House', 20 accommodatesNumber: '2', 21 maximumNumberOfNights: '30' 22 }, 23 { 24 lastScrapedDate: '2019-02-18', 25 propertyName: '4floor house in Taksim,Taksimde 4katli müstakil ev', 26 propertyType: 'House', 27 accommodatesNumber: '2', 28 maximumNumberOfNights: '30' 29 }, 30 { 31 lastScrapedDate: '2019-02-16', 32 propertyName: '22 Oporto Guesthouse Cordoaria', 33 propertyType: 'House', 34 accommodatesNumber: '2', 35 maximumNumberOfNights: '30' 36 } 37
以下查询搜索以 2
开头的某个时间列出的属性,并允许以 1
开头的住宿天数。
db.airbnb_mat_view.aggregate([ { "$search": { "index": "date-number-fields-tutorial", "compound": { "should": [{ "autocomplete": { "path": "lastScrapedDate", "query": "2" } }, { "autocomplete": { "path": "maximumNumberOfNights", "query": "1" } }] } } }, { $limit: 5 }, { $project: { "_id": 0 } } ])
[ { lastScrapedDate: '2019-02-11', propertyName: 'Horto flat with small garden', propertyType: 'Apartment', accommodatesNumber: '4', maximumNumberOfNights: '1125' }, { lastScrapedDate: '2019-03-06', propertyName: 'Private Room in Bushwick', propertyType: 'Apartment', accommodatesNumber: '1', maximumNumberOfNights: '1125' }, { lastScrapedDate: '2019-02-11', propertyName: 'Apt Linda Vista Lagoa - Rio', propertyType: 'Apartment', accommodatesNumber: '2', maximumNumberOfNights: '1125' }, { lastScrapedDate: '2019-02-18', propertyName: 'Charming Flat in Downtown Moda', propertyType: 'House', accommodatesNumber: '6', maximumNumberOfNights: '1125' }, { lastScrapedDate: '2019-02-11', propertyName: "Catete's Colonial Big Hause Room B", propertyType: 'House', accommodatesNumber: '8', maximumNumberOfNights: '1125' } ]
以下查询会搜索那些住宿天数以 3
开头并且能够容纳以 2
开头的人数的酒店。
db.airbnb_mat_view.aggregate([ { "$search": { "index": "date-number-fields-tutorial", "compound": { "should": [{ "autocomplete": { "path": "maximumNumberOfNights", "query": "3" } }, { "autocomplete": { "path": "accommodatesNumber", "query": "2" } }] } } }, { $limit: 5 }, { $project: { "_id": 0 } } ])
[ { lastScrapedDate: '2019-03-06', propertyName: 'Ocean View Waikiki Marina w/prkg', propertyType: 'Condominium', accommodatesNumber: '2', maximumNumberOfNights: '365' }, { lastScrapedDate: '2019-03-07', propertyName: 'New York City - Upper West Side Apt', propertyType: 'Apartment', accommodatesNumber: '2', maximumNumberOfNights: '360' }, { lastScrapedDate: '2019-03-07', propertyName: 'Sydney Hyde Park City Apartment (checkin from 6am)', propertyType: 'Apartment', accommodatesNumber: '2', maximumNumberOfNights: '30' }, { lastScrapedDate: '2019-03-07', propertyName: 'Private Room (2) in Guest House at Coogee Beach', propertyType: 'House', accommodatesNumber: '2', maximumNumberOfNights: '365' }, { lastScrapedDate: '2019-03-06', propertyName: '~Ao Lele~ Flying Cloud', propertyType: 'Treehouse', accommodatesNumber: '2', maximumNumberOfNights: '30' } ]
在 MongoDB Compass 中连接到您的集群。
打开 MongoDB Compass 并连接到您的集群。有关连接的详细说明,请参阅通过 Compass 连接。
使用您为其创建索引的操作符运行以下 Atlas Search 查询。
如果创建了使用动态映射的索引,您可以使用 queryString 操作符查询 airbnb_mat_view
集合。如果创建了使用静态映射的索引,您可以使用 autocomplete 操作符查询 airbnb_mat_view
集合。
以下查询搜索房产类型为 Apartment
或 Condominium
,可容纳 2
个人并在 2019
中列出的房产。
管道阶段 | 查询 | |||||||
---|---|---|---|---|---|---|---|---|
$search |
| |||||||
$limit |
| |||||||
$project |
|
如果启用了 Auto Preview,MongoDB Compass 将在 $project
管道阶段旁边显示以下文档:
1 [ 2 { 3 lastScrapedDate: '2019-03-06', 4 propertyName: 'LAHAINA, MAUI! RESORT/CONDO BEACHFRONT!! SLEEPS 4!', 5 propertyType: 'Condominium', 6 accommodatesNumber: '4' 7 }, 8 { 9 lastScrapedDate: '2019-03-06', 10 propertyName: 'Makaha Valley Paradise with OceanView', 11 propertyType: 'Condominium', 12 accommodatesNumber: '4' 13 }, 14 { 15 lastScrapedDate: '2019-03-06', 16 propertyName: 'March 2019 availability! Oceanview on Sugar Beach!', 17 propertyType: 'Condominium', 18 accommodatesNumber: '4' 19 }, 20 { 21 lastScrapedDate: '2019-03-06', 22 propertyName: 'Tropical Jungle Oasis', 23 propertyType: 'Condominium', 24 accommodatesNumber: '4' 25 }, 26 { 27 lastScrapedDate: '2019-02-11', 28 propertyName: 'Hospede-se com acesso fácil.', 29 propertyType: 'Condominium', 30 accommodatesNumber: '4' 31 } 32 ] 33
以下查询搜索房产类型为House
、可容纳2
人、列在2019
中或最多允许住宿晚数30
晚的房产。
管道阶段 | 查询 | |||||||
---|---|---|---|---|---|---|---|---|
$search |
| |||||||
$limit |
| |||||||
$project |
|
如果启用了 Auto Preview,MongoDB Compass 将在 $project
管道阶段旁边显示以下文档:
1 [ 2 { 3 lastScrapedDate: '2019-02-11', 4 propertyName: '2017 , férias no Rio', 5 propertyType: 'House', 6 accommodatesNumber: '2', 7 maximumNumberOfNights: '30' 8 }, 9 { 10 lastScrapedDate: '2019-03-07', 11 propertyName: 'Newly renovated home', 12 propertyType: 'House', 13 accommodatesNumber: '2', 14 maximumNumberOfNights: '30' 15 }, 16 { 17 lastScrapedDate: '2019-02-18', 18 propertyName: 'Vintage House For Rent', 19 propertyType: 'House', 20 accommodatesNumber: '2', 21 maximumNumberOfNights: '30' 22 }, 23 { 24 lastScrapedDate: '2019-02-18', 25 propertyName: '4floor house in Taksim,Taksimde 4katli müstakil ev', 26 propertyType: 'House', 27 accommodatesNumber: '2', 28 maximumNumberOfNights: '30' 29 }, 30 { 31 lastScrapedDate: '2019-02-16', 32 propertyName: '22 Oporto Guesthouse Cordoaria', 33 propertyType: 'House', 34 accommodatesNumber: '2', 35 maximumNumberOfNights: '30' 36 } 37
以下查询搜索以 2
开头的某个时间列出的属性,并允许以 1
开头的住宿天数。
管道阶段 | 查询 | |||||||||||||||||
---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|
$search |
| |||||||||||||||||
$limit |
| |||||||||||||||||
$project |
|
如果启用了 Auto Preview,MongoDB Compass 将在 $project
管道阶段旁边显示以下文档:
1 [ 2 { 3 lastScrapedDate: '2019-02-11', 4 propertyName: 'Horto flat with small garden', 5 propertyType: 'Apartment', 6 accommodatesNumber: '4', 7 maximumNumberOfNights: '1125' 8 }, 9 { 10 lastScrapedDate: '2019-03-06', 11 propertyName: 'Private Room in Bushwick', 12 propertyType: 'Apartment', 13 accommodatesNumber: '1', 14 maximumNumberOfNights: '1125' 15 }, 16 { 17 lastScrapedDate: '2019-02-11', 18 propertyName: 'Apt Linda Vista Lagoa - Rio', 19 propertyType: 'Apartment', 20 accommodatesNumber: '2', 21 maximumNumberOfNights: '1125' 22 }, 23 { 24 lastScrapedDate: '2019-02-18', 25 propertyName: 'Charming Flat in Downtown Moda', 26 propertyType: 'House', 27 accommodatesNumber: '6', 28 maximumNumberOfNights: '1125' 29 }, 30 { 31 lastScrapedDate: '2019-02-11', 32 propertyName: "Catete's Colonial Big Hause Room B", 33 propertyType: 'House', 34 accommodatesNumber: '8', 35 maximumNumberOfNights: '1125' 36 } 37 ]
以下查询会搜索那些住宿天数以 3
开头并且能够容纳以 2
开头的人数的酒店。
管道阶段 | 查询 | |||||||||||||||||
---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|
$search |
| |||||||||||||||||
$limit |
| |||||||||||||||||
$project |
|
如果启用了 Auto Preview,MongoDB Compass 将在 $project
管道阶段旁边显示以下文档:
1 [ 2 { 3 lastScrapedDate: '2019-03-06', 4 propertyName: 'Ocean View Waikiki Marina w/prkg', 5 propertyType: 'Condominium', 6 accommodatesNumber: '2', 7 maximumNumberOfNights: '365' 8 }, 9 { 10 lastScrapedDate: '2019-03-07', 11 propertyName: 'New York City - Upper West Side Apt', 12 propertyType: 'Apartment', 13 accommodatesNumber: '2', 14 maximumNumberOfNights: '360' 15 }, 16 { 17 lastScrapedDate: '2019-03-07', 18 propertyName: 'Sydney Hyde Park City Apartment (checkin from 6am)', 19 propertyType: 'Apartment', 20 accommodatesNumber: '2', 21 maximumNumberOfNights: '30' 22 }, 23 { 24 lastScrapedDate: '2019-03-07', 25 propertyName: 'Private Room (2) in Guest House at Coogee Beach', 26 propertyType: 'House', 27 accommodatesNumber: '2', 28 maximumNumberOfNights: '365' 29 }, 30 { 31 lastScrapedDate: '2019-03-06', 32 propertyName: '~Ao Lele~ Flying Cloud', 33 propertyType: 'Treehouse', 34 accommodatesNumber: '2', 35 maximumNumberOfNights: '30' 36 } 37 ]
使用以下代码替换 Program.cs
文件中的内容,这些代码适用于创建索引的操作符和希望运行的查询类型。
如果创建了使用动态映射的索引,您可以使用 queryString 操作符查询 airbnb_mat_view
集合。如果创建了使用静态映射的索引,您可以使用 autocomplete 操作符查询 airbnb_mat_view
集合。
此代码示例将执行以下任务:
导入
mongodb
包和依赖项。建立与您的 Atlas 集群的连接。
遍历游标以打印与查询匹配的文档。
以下查询搜索房产类型为 Apartment
或 Condominium
,可容纳 2
个人并在 2019
中列出的房产。
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 DateNumberToStringQuery 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 airbnbDatabase = mongoClient.GetDatabase("sample_airbnb"); 20 var matViewCollection = airbnbDatabase.GetCollection<matViewDocument>("airbnb_mat_view"); 21 22 // define and run pipeline 23 var results = matViewCollection.Aggregate() 24 .Search(Builders<matViewDocument>.Search.QueryString( 25 airbnb => airbnb.propertyType, 26 "(Apartment OR Condominium) AND accommodatesNumber: 4 AND lastScrapedDate: 2019" 27 ), 28 indexName: "date-number-fields-tutorial") 29 .Limit(5) 30 .Project<matViewDocument>(Builders<matViewDocument>.Projection 31 .Exclude(airbnb => airbnb.Id)) 32 .ToList(); 33 34 // print results 35 foreach (var airbnb in results) 36 { 37 Console.WriteLine(airbnb.ToJson()); 38 } 39 } 40 } 41 42 [ ]43 public class matViewDocument 44 { 45 [ ]46 public string Id { get; set; } 47 public string lastScrapedDate { get; set; } 48 public string propertyName { get; set; } 49 public string propertyType { get; set; } 50 public string accommodatesNumber { get; set; } 51 public string maximumNumberOfNights { get; set; } 52 }
在运行示例之前,请将 <connection-string>
替换为 Atlas 连接字符串。确保您的连接字符串包含数据库用户的档案。要了解详情,请参阅通过驱动程序连接。
以下查询搜索房产类型为House
、可容纳2
人、列在2019
中或最多允许住宿晚数30
晚的房产。
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 DateNumberToStringQuery 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 var ConventionRegistry.Register("CamelCase", camelCaseConvention, type => true); 16 17 // connect to your Atlas cluster 18 var mongoClient = new MongoClient(MongoConnectionString); 19 var airbnbDatabase = mongoClient.GetDatabase("sample_airbnb"); 20 var matViewCollection = airbnbDatabase.GetCollection<matViewDocument>("airbnb_mat_view"); 21 22 // define and run pipeline 23 var results = matViewCollection.Aggregate() 24 .Search(Builders<matViewDocument>.Search.QueryString( 25 airbnb => airbnb.propertyType, 26 "House OR accommodatesNumber: 2 OR lastScrapedDate: 2019 OR maximumNumberOfNights: 30" 27 ), 28 indexName: "date-number-fields-tutorial") 29 .Limit(5) 30 .Project<matViewDocument>(Builders<matViewDocument>.Projection 31 .Exclude(airbnb => airbnb.Id)) 32 .ToList(); 33 34 // print results 35 foreach (var airbnb in results) 36 { 37 Console.WriteLine(airbnb.ToJson()); 38 } 39 } 40 } 41 42 [ ]43 public class matViewDocument 44 { 45 [ ]46 public string Id { get; set; } 47 public string lastScrapedDate { get; set; } 48 public string propertyName { get; set; } 49 public string propertyType { get; set; } 50 public string accommodatesNumber { get; set; } 51 public string maximumNumberOfNights { get; set; } 52 }
在运行示例之前,请将 <connection-string>
替换为 Atlas 连接字符串。确保您的连接字符串包含数据库用户的档案。要了解详情,请参阅通过驱动程序连接。
此代码示例将执行以下任务:
导入
mongodb
包和依赖项。建立与您的 Atlas 集群的连接。
遍历游标以打印与查询匹配的文档。
以下查询搜索以 2
开头的某个时间列出的属性,并允许以 1
开头的住宿天数。
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 DateNumberToStringQuery 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 airbnbDatabase = mongoClient.GetDatabase("sample_airbnb"); 20 var matViewCollection = airbnbDatabase.GetCollection<matViewDocument>("airbnb_mat_view"); 21 22 // define and run pipeline 23 var results = matViewCollection.Aggregate() 24 .Search(Builders<matViewDocument>.Search.Compound() 25 .Should(Builders<matViewDocument>.Search.Autocomplete(airbnb => airbnb.lastScrapedDate, "2")) 26 .Should(Builders<matViewDocument>.Search.Autocomplete(airbnb => airbnb.maximumNumberOfNights, "1")), 27 indexName: "date-number-fields-tutorial") 28 .Limit(5) 29 .Project<matViewDocument>(Builders<matViewDocument>.Projection 30 .Exclude(airbnb => airbnb.Id)) 31 .ToList(); 32 33 // print results 34 foreach (var airbnb in results) 35 { 36 Console.WriteLine(airbnb.ToJson()); 37 } 38 } 39 } 40 41 [ ]42 public class matViewDocument 43 { 44 [ ]45 public string Id { get; set; } 46 public string lastScrapedDate { get; set; } 47 public string propertyName { get; set; } 48 public string propertyType { get; set; } 49 public string accommodatesNumber { get; set; } 50 public string maximumNumberOfNights { get; set; } 51 }
在运行示例之前,请将 <connection-string>
替换为 Atlas 连接字符串。确保您的连接字符串包含数据库用户的档案。要了解详情,请参阅通过驱动程序连接。
以下查询会搜索那些住宿天数以 3
开头并且能够容纳以 2
开头的人数的酒店。
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 DateNumberToStringQuery 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 airbnbDatabase = mongoClient.GetDatabase("sample_airbnb"); 20 var matViewCollection = airbnbDatabase.GetCollection<matViewDocument>("airbnb_mat_view"); 21 22 // define and run pipeline 23 var results = matViewCollection.Aggregate() 24 .Search(Builders<matViewDocument>.Search.Compound() 25 .Should(Builders<matViewDocument>.Search.Autocomplete(airbnb => airbnb.maximumNumberOfNights, "3")) 26 .Should(Builders<matViewDocument>.Search.Autocomplete(airbnb => airbnb.accommodatesNumber, "2")), 27 indexName: "date-number-fields-tutorial") 28 .Limit(5) 29 .Project<matViewDocument>(Builders<matViewDocument>.Projection 30 .Exclude(airbnb => airbnb.Id)) 31 .ToList(); 32 33 // print results 34 foreach (var airbnb in results) 35 { 36 Console.WriteLine(airbnb.ToJson()); 37 } 38 } 39 } 40 41 [ ]42 public class matViewDocument 43 { 44 [ ]45 public string Id { get; set; } 46 public string lastScrapedDate { get; set; } 47 public string propertyName { get; set; } 48 public string propertyType { get; set; } 49 public string accommodatesNumber { get; set; } 50 public string maximumNumberOfNights { get; set; } 51 }
在运行示例之前,请将 <connection-string>
替换为 Atlas 连接字符串。确保您的连接字符串包含数据库用户的档案。要了解详情,请参阅通过驱动程序连接。
编译并运行 Program.cs
文件。
dotnet run Program.cs
1 { 2 "lastScrapedDate": "2019-03-06", 3 "propertyName": "LAHAINA, MAUI! RESORT/CONDO BEACHFRONT!! SLEEPS 4!", 4 "propertyType": "Condominium", 5 "accommodatesNumber": "4", 6 "maximumNumberOfNights": "1125" 7 } 8 { 9 "lastScrapedDate": "2019-03-06", 10 "propertyName": "Makaha Valley Paradise with OceanView", 11 "propertyType": "Condominium", 12 "accommodatesNumber": "4", 13 "maximumNumberOfNights": "180" 14 } 15 { 16 "lastScrapedDate": "2019-03-06", 17 "propertyName": "March 2019 availability! Oceanview on Sugar Beach!", 18 "propertyType": "Condominium", 19 "accommodatesNumber": "4", 20 "maximumNumberOfNights": "1125" 21 } 22 { 23 "lastScrapedDate": "2019-03-06", 24 "propertyName": "Tropical Jungle Oasis", 25 "propertyType": "Condominium", 26 "accommodatesNumber": "4", 27 "maximumNumberOfNights": "1125" 28 } 29 { 30 "lastScrapedDate": "2019-02-11", 31 "propertyName": "Hospede-se com acesso fácil.", 32 "propertyType": "Condominium", 33 "accommodatesNumber": "4", 34 "maximumNumberOfNights": "1125" 35 }
dotnet run Program.cs
1 { 2 "lastScrapedDate": "2019-02-11", 3 "propertyName": "2017 , férias no Rio", 4 "propertyType": "House", 5 "accommodatesNumber": "2", 6 "maximumNumberOfNights": "30" 7 } 8 { 9 "lastScrapedDate": "2019-03-07", 10 "propertyName": "Newly renovated home", 11 "propertyType": "House", 12 "accommodatesNumber": "2", 13 "maximumNumberOfNights": "30" 14 } 15 { 16 "lastScrapedDate": "2019-02-18", 17 "propertyName": "Vintage House For Rent", 18 "propertyType": "House", 19 "accommodatesNumber": "2", 20 "maximumNumberOfNights": "30" 21 } 22 { 23 "lastScrapedDate": "2019-02-18", 24 "propertyName": "4floor house in Taksim,Taksimde 4katli müstakil ev", 25 "propertyType": "House", 26 "accommodatesNumber": "2", 27 "maximumNumberOfNights": "30" 28 } 29 { 30 "lastScrapedDate": "2019-02-16", 31 "propertyName": "22 Oporto Guesthouse Cordoaria", 32 "propertyType": "House", 33 "accommodatesNumber": "2", 34 "maximumNumberOfNights": "30" 35 }
dotnet run Program.cs
1 { 2 "lastScrapedDate": "2019-02-11", 3 "propertyName": "Horto flat with small garden", 4 "propertyType": "Apartment", 5 "accommodatesNumber": "4", 6 "maximumNumberOfNights": "1125" 7 } 8 { 9 "lastScrapedDate": "2019-03-06", 10 "propertyName": "Private Room in Bushwick", 11 "propertyType": "Apartment", 12 "accommodatesNumber": "1", 13 "maximumNumberOfNights": "1125" 14 } 15 { 16 "lastScrapedDate": "2019-02-11", 17 "propertyName": "Apt Linda Vista Lagoa - Rio", 18 "propertyType": "Apartment", 19 "accommodatesNumber": "2", 20 "maximumNumberOfNights": "1125" 21 } 22 { 23 "lastScrapedDate": "2019-02-18", 24 "propertyName": "Charming Flat in Downtown Moda", 25 "propertyType": "House", 26 "accommodatesNumber": "6", 27 "maximumNumberOfNights": "1125" 28 } 29 { 30 "lastScrapedDate": "2019-02-11", 31 "propertyName": "Catete's Colonial Big Hause Room B", 32 "propertyType": "House", 33 "accommodatesNumber": "8", 34 "maximumNumberOfNights": "1125" 35 }
dotnet run Program.cs
1 { 2 "lastScrapedDate": "2019-03-06", 3 "propertyName": "Ocean View Waikiki Marina w/prkg", 4 "propertyType": "Condominium", 5 "accommodatesNumber": "2", 6 "maximumNumberOfNights": "365" 7 } 8 { 9 "lastScrapedDate": "2019-03-07", 10 "propertyName": "New York City - Upper West Side Apt", 11 "propertyType": "Apartment", 12 "accommodatesNumber": "2", 13 "maximumNumberOfNights": "360" 14 } 15 { 16 "lastScrapedDate": "2019-03-07", 17 "propertyName": "Sydney Hyde Park City Apartment (checkin from 6am)", 18 "propertyType": "Apartment", 19 "accommodatesNumber": "2", 20 "maximumNumberOfNights": "30" 21 } 22 { 23 "lastScrapedDate": "2019-03-07", 24 "propertyName": "Private Room (2) in Guest House at Coogee Beach", 25 "propertyType": "House", 26 "accommodatesNumber": "2", 27 "maximumNumberOfNights": "365" 28 } 29 { 30 "lastScrapedDate": "2019-03-06", 31 "propertyName": "~Ao Lele~ Flying Cloud", 32 "propertyType": "Treehouse", 33 "accommodatesNumber": "2", 34 "maximumNumberOfNights": "30" 35 }
将创建索引的操作符的代码示例复制并粘贴到 date-number-to-string-query.go
文件中。
如果创建了使用动态映射的索引,您可以使用 queryString 操作符查询 airbnb_mat_view
集合。如果创建了使用静态映射的索引,您可以使用 autocomplete 操作符查询 airbnb_mat_view
集合。
以下查询搜索房产类型为 Apartment
或 Condominium
,可容纳 2
个人并在 2019
中列出的房产。
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 var err error 15 // connect to the Atlas cluster 16 ctx := context.Background() 17 client, err := mongo.Connect(ctx, options.Client().ApplyURI("<connection-string>")) 18 if err != nil { 19 panic(err) 20 } 21 defer client.Disconnect(ctx) 22 // set namespace 23 collection := client.Database("sample_airbnb").Collection("airbnb_mat_view") 24 // define pipeline 25 searchStage := bson.D{{"$search", bson.D{ 26 {"index", "date-number-fields-tutorial"}, 27 {"queryString", bson.D{ 28 {"defaultPath", "propertyType"}, 29 {"query", "propertyType: (Apartment OR Condominium) AND accommodatesNumber: 4 AND lastScrapedDate: 2019"}, 30 }}}}} 31 limitStage := bson.D{{"$limit", 5}} 32 projectStage := bson.D{{"$project", bson.D{{"_id", 0}}}} 33 // specify the amount of time the operation can run on the server 34 opts := options.Aggregate().SetMaxTime(5 * time.Second) 35 // run pipeline 36 cursor, err := collection.Aggregate(ctx, mongo.Pipeline{searchStage, limitStage, projectStage}, opts) 37 if err != nil { 38 panic(err) 39 } 40 // print results 41 var results []bson.D 42 if err = cursor.All(context.TODO(), &results); err != nil { 43 panic(err) 44 } 45 for _, result := range results { 46 fmt.Println(result) 47 } 48 }
在运行示例之前,请将 <connection-string>
替换为 Atlas 连接字符串。确保您的连接字符串包含数据库用户的档案。要了解详情,请参阅通过驱动程序连接。
以下查询搜索房产类型为House
、可容纳2
人、列在2019
中或最多允许住宿晚数30
晚的房产。
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 var err error 15 // connect to the Atlas cluster 16 ctx := context.Background() 17 client, err := mongo.Connect(ctx, options.Client().ApplyURI("<connection-string>")) 18 if err != nil { 19 panic(err) 20 } 21 defer client.Disconnect(ctx) 22 // set namespace 23 collection := client.Database("sample_airbnb").Collection("airbnb_mat_view") 24 // define pipeline 25 searchStage := bson.D{{"$search", bson.D{ 26 {"index", "date-number-fields-tutorial"}, 27 {"queryString", bson.D{ 28 {"defaultPath", "propertyType"}, 29 {"query", "propertyType: House OR accommodatesNumber: 2 OR lastScrapedDate: 2019 OR maximumNumberOfNights: 30"}, 30 }}}}} 31 limitStage := bson.D{{"$limit", 5}} 32 projectStage := bson.D{{"$project", bson.D{{"_id", 0}}}} 33 // specify the amount of time the operation can run on the server 34 opts := options.Aggregate().SetMaxTime(5 * time.Second) 35 // run pipeline 36 cursor, err := collection.Aggregate(ctx, mongo.Pipeline{searchStage, limitStage, projectStage}, opts) 37 if err != nil { 38 panic(err) 39 } 40 // print results 41 var results []bson.D 42 if err = cursor.All(context.TODO(), &results); err != nil { 43 panic(err) 44 } 45 for _, result := range results { 46 fmt.Println(result) 47 } 48 }
在运行示例之前,请将 <connection-string>
替换为 Atlas 连接字符串。确保您的连接字符串包含数据库用户的档案。要了解详情,请参阅通过驱动程序连接。
以下查询搜索以 2
开头的某个时间列出的属性,并允许以 1
开头的住宿天数。
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 // define structure of movies collection 14 type MovieCollection struct { 15 title string `bson:"Title,omitempty"` 16 } 17 18 func main() { 19 var err error 20 // connect to the Atlas cluster 21 ctx := context.Background() 22 client, err := mongo.Connect(ctx, options.Client().ApplyURI("<connection-tring>")) 23 if err != nil { 24 panic(err) 25 } 26 defer client.Disconnect(ctx) 27 // set namespace 28 collection := client.Database("sample_airbnb").Collection("airbnb_mat_view") 29 // define pipeline 30 searchStage := bson.D{{"$search", bson.M{ 31 "index": "date-number-fields-tutorial", 32 "compound": bson.M{ 33 "should": bson.A{ 34 bson.M{ 35 "autocomplete": bson.M{ 36 "path": "lastScrapedDate", "query": "2", 37 }, 38 }, 39 bson.M{ 40 "autocomplete": bson.M{ 41 "path": "maximumNumberOfNights", "query": "1", 42 }, 43 }, 44 }, 45 }, 46 }}} 47 limitStage := bson.D{{"$limit", 5}} 48 projectStage := bson.D{{"$project", bson.D{{"_id", 0}}}} 49 // specify the amount of time the operation can run on the server 50 opts := options.Aggregate().SetMaxTime(5 * time.Second) 51 // run pipeline 52 cursor, err := collection.Aggregate(ctx, mongo.Pipeline{searchStage, limitStage, projectStage}, opts) 53 if err != nil { 54 panic(err) 55 } 56 // print results 57 var results []bson.D 58 if err = cursor.All(context.TODO(), &results); err != nil { 59 panic(err) 60 } 61 for _, result := range results { 62 fmt.Println(result) 63 } 64 }
在运行示例之前,请将 <connection-string>
替换为 Atlas 连接字符串。确保您的连接字符串包含数据库用户的档案。要了解详情,请参阅通过驱动程序连接。
以下查询会搜索那些住宿天数以 3
开头并且能够容纳以 2
开头的人数的酒店。
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 // define structure of movies collection 14 type MovieCollection struct { 15 title string `bson:"Title,omitempty"` 16 } 17 18 func main() { 19 var err error 20 // connect to the Atlas cluster 21 ctx := context.Background() 22 client, err := mongo.Connect(ctx, options.Client().ApplyURI("<connection-string>")) 23 if err != nil { 24 panic(err) 25 } 26 defer client.Disconnect(ctx) 27 // set namespace 28 collection := client.Database("sample_airbnb").Collection("airbnb_mat_view") 29 // define pipeline 30 searchStage := bson.D{{"$search", bson.M{ 31 "index": "date-number-fields-tutorial", 32 "compound": bson.M{ 33 "should": bson.A{ 34 bson.M{ 35 "autocomplete": bson.M{ 36 "path": "maximumNumberOfNights", "query": "3", 37 }, 38 }, 39 bson.M{ 40 "autocomplete": bson.M{ 41 "path": "accommodatesNumber", "query": "2", 42 }, 43 }, 44 }, 45 }, 46 }}} 47 limitStage := bson.D{{"$limit", 5}} 48 projectStage := bson.D{{"$project", bson.D{{"_id", 0}}}} 49 // specify the amount of time the operation can run on the server 50 opts := options.Aggregate().SetMaxTime(5 * time.Second) 51 // run pipeline 52 cursor, err := collection.Aggregate(ctx, mongo.Pipeline{searchStage, limitStage, projectStage}, opts) 53 if err != nil { 54 panic(err) 55 } 56 // print results 57 var results []bson.D 58 if err = cursor.All(context.TODO(), &results); err != nil { 59 panic(err) 60 } 61 for _, result := range results { 62 fmt.Println(result) 63 } 64 }
在运行示例之前,请将 <connection-string>
替换为 Atlas 连接字符串。确保您的连接字符串包含数据库用户的档案。要了解详情,请参阅通过驱动程序连接。
运行以下命令来查询您的集合:
go run date-number-to-string-query.go
1 [ 2 {lastScrapedDate 2019-03-06} 3 {propertyName LAHAINA, MAUI! RESORT/CONDO BEACHFRONT!! SLEEPS 4!} 4 {propertyType Condominium} 5 {accommodatesNumber 4} 6 {maximumNumberOfNights 1125} 7 ] 8 [ 9 {lastScrapedDate 2019-03-06} 10 {propertyName Makaha Valley Paradise with OceanView} 11 {propertyType Condominium} 12 {accommodatesNumber 4} 13 {maximumNumberOfNights 180} 14 ] 15 [ 16 {lastScrapedDate 2019-03-06} 17 {propertyName March 2019 availability! Oceanview on Sugar Beach!} 18 {propertyType Condominium} 19 {accommodatesNumber 4} 20 {maximumNumberOfNights 1125} 21 ] 22 [ 23 {lastScrapedDate 2019-03-06} 24 {propertyName Tropical Jungle Oasis} 25 {propertyType Condominium} 26 {accommodatesNumber 4} 27 {maximumNumberOfNights 1125} 28 ] 29 [ 30 {lastScrapedDate 2019-02-11} 31 {propertyName Hospede-se com acesso fácil.} 32 {propertyType Condominium} 33 {accommodatesNumber 4} 34 {maximumNumberOfNights 1125} 35 ]
go run date-number-to-string-query.go
1 [ 2 {lastScrapedDate 2019-02-11} 3 {propertyName 2017 , férias no Rio} 4 {propertyType House} 5 {accommodatesNumber 2} 6 {maximumNumberOfNights 30} 7 ] 8 [ 9 {lastScrapedDate 2019-03-07} 10 {propertyName Newly renovated home} 11 {propertyType House} 12 {accommodatesNumber 2} 13 {maximumNumberOfNights 30} 14 ] 15 [ 16 {lastScrapedDate 2019-02-18} 17 {propertyName Vintage House For Rent} 18 {propertyType House} 19 {accommodatesNumber 2} 20 {maximumNumberOfNights 30} 21 ] 22 [ 23 {lastScrapedDate 2019-02-18} 24 {propertyName 4floor house in Taksim,Taksimde 4katli müstakil ev} 25 {propertyType House} 26 {accommodatesNumber 2} 27 {maximumNumberOfNights 30} 28 ] 29 [ 30 {lastScrapedDate 2019-02-16} 31 {propertyName 22 Oporto Guesthouse Cordoaria} 32 {propertyType House} 33 {accommodatesNumber 2} 34 {maximumNumberOfNights 30} 35 ]
go run date-number-to-string-query.go
1 [ 2 {lastScrapedDate 2019-02-11} 3 {propertyName Horto flat with small garden} 4 {propertyType Apartment} 5 {accommodatesNumber 4} 6 {maximumNumberOfNights 1125} 7 ] 8 [ 9 {lastScrapedDate 2019-03-06} 10 {propertyName Private Room in Bushwick} 11 {propertyType Apartment} 12 {accommodatesNumber 1} 13 {maximumNumberOfNights 1125} 14 ] 15 [ 16 {lastScrapedDate 2019-02-11} 17 {propertyName Apt Linda Vista Lagoa - Rio} 18 {propertyType Apartment} 19 {accommodatesNumber 2} 20 {maximumNumberOfNights 1125} 21 ] 22 [ 23 {lastScrapedDate 2019-02-18} 24 {propertyName Charming Flat in Downtown Moda} 25 {propertyType House} 26 {accommodatesNumber 6} 27 {maximumNumberOfNights 1125} 28 ] 29 [ 30 {lastScrapedDate 2019-02-11} 31 {propertyName Catete's Colonial Big Hause Room B} 32 {propertyType House} 33 {accommodatesNumber 8} 34 {maximumNumberOfNights 1125} 35 ]
go run date-number-to-string-query.go
1 [ 2 {lastScrapedDate 2019-03-06} 3 {propertyName Ocean View Waikiki Marina w/prkg} 4 {propertyType Condominium} 5 {accommodatesNumber 2} 6 {maximumNumberOfNights 365} 7 ] 8 [ 9 {lastScrapedDate 2019-03-07} 10 {propertyName New York City - Upper West Side Apt} 11 {propertyType Apartment} 12 {accommodatesNumber 2} 13 {maximumNumberOfNights 360} 14 ] 15 [ 16 {lastScrapedDate 2019-03-07} 17 {propertyName Sydney Hyde Park City Apartment (checkin from 6am)} 18 {propertyType Apartment} 19 {accommodatesNumber 2} 20 {maximumNumberOfNights 30} 21 ] 22 [ 23 {lastScrapedDate 2019-03-07} 24 {propertyName Private Room (2) in Guest House at Coogee Beach} 25 {propertyType House} 26 {accommodatesNumber 2} 27 {maximumNumberOfNights 365} 28 ] 29 [ 30 {lastScrapedDate 2019-03-06} 31 {propertyName ~Ao Lele~ Flying Cloud} 32 {propertyType Treehouse} 33 {accommodatesNumber 2} 34 {maximumNumberOfNights 30} 35 ]
将创建索引的操作符代码复制并粘贴到 DateNumberToStringQuery.java
文件中。
如果创建了使用动态映射的索引,您可以使用 queryString 操作符查询 airbnb_mat_view
集合。如果创建了使用静态映射的索引,您可以使用 autocomplete 操作符查询 airbnb_mat_view
集合。
此代码示例将执行以下任务:
导入
mongodb
包和依赖项。建立与您的 Atlas 集群的连接。
遍历游标以打印与查询匹配的文档。
注意
要在 Maven 环境中运行示例代码,请在文件中的 import 语句上方添加以下内容。
package com.mongodb.drivers;
以下查询搜索房产类型为 Apartment
或 Condominium
,可容纳 2
个人并在 2019
中列出的房产。
1 import java.util.Arrays; 2 import static com.mongodb.client.model.Filters.eq; 3 import static com.mongodb.client.model.Aggregates.limit; 4 import static com.mongodb.client.model.Aggregates.project; 5 import static com.mongodb.client.model.Projections.excludeId; 6 import static com.mongodb.client.model.Projections.fields; 7 import com.mongodb.client.MongoClient; 8 import com.mongodb.client.MongoClients; 9 import com.mongodb.client.MongoCollection; 10 import com.mongodb.client.MongoDatabase; 11 import org.bson.Document; 12 13 public class DateNumberToStringQuery { 14 public static void main( String[] args ) { 15 // define query 16 Document agg = new Document("$search", 17 new Document ("index", "date-number-fields-tutorial") 18 .append("queryString", 19 new Document("defaultPath", "propertyType") 20 .append("query", "propertyType: (Apartment OR Condominium) AND accommodatesNumber: 4 AND lastScrapedDate: 2019"))); 21 22 // specify connection 23 String uri = "<connection-string>"; 24 25 // establish connection and set namespace 26 try (MongoClient mongoClient = MongoClients.create(uri)) { 27 MongoDatabase database = mongoClient.getDatabase("sample_airbnb"); 28 MongoCollection<Document> collection = database.getCollection("airbnb_mat_view"); 29 // run query and print results 30 collection.aggregate(Arrays.asList(agg, 31 limit(5), 32 project(fields(excludeId()) )) 33 ).forEach(doc -> System.out.println(doc.toJson())); 34 } 35 } 36 }
在运行示例之前,请将 <connection-string>
替换为 Atlas 连接字符串。确保您的连接字符串包含数据库用户的档案。要了解详情,请参阅通过驱动程序连接。
以下查询搜索房产类型为House
、可容纳2
人、列在2019
中或最多允许住宿晚数30
晚的房产。
1 import java.util.Arrays; 2 import static com.mongodb.client.model.Filters.eq; 3 import static com.mongodb.client.model.Aggregates.limit; 4 import static com.mongodb.client.model.Aggregates.project; 5 import static com.mongodb.client.model.Projections.excludeId; 6 import static com.mongodb.client.model.Projections.fields; 7 import com.mongodb.client.MongoClient; 8 import com.mongodb.client.MongoClients; 9 import com.mongodb.client.MongoCollection; 10 import com.mongodb.client.MongoDatabase; 11 import org.bson.Document; 12 13 public class DateNumberToStringQuery { 14 public static void main( String[] args ) { 15 // define query 16 Document agg = new Document("$search", 17 new Document ("index", "date-number-fields-tutorial") 18 .append("queryString", 19 new Document("defaultPath", "propertyType") 20 .append("query", "propertyType: House OR accommodatesNumber: 2 OR lastScrapedDate: 2019 OR maximumNumberOfNights: 30"))); 21 22 // specify connection 23 String uri = "<connection-string>"; 24 25 // establish connection and set namespace 26 try (MongoClient mongoClient = MongoClients.create(uri)) { 27 MongoDatabase database = mongoClient.getDatabase("sample_airbnb"); 28 MongoCollection<Document> collection = database.getCollection("airbnb_mat_view"); 29 // run query and print results 30 collection.aggregate(Arrays.asList(agg, 31 limit(5), 32 project(fields(excludeId()) )) 33 ).forEach(doc -> System.out.println(doc.toJson())); 34 } 35 } 36 }
在运行示例之前,请将 <connection-string>
替换为 Atlas 连接字符串。确保您的连接字符串包含数据库用户的档案。要了解详情,请参阅通过驱动程序连接。
此代码示例将执行以下任务:
导入
mongodb
包和依赖项。建立与您的 Atlas 集群的连接。
遍历游标以打印与查询匹配的文档。
注意
要在 Maven 环境中运行示例代码,请在文件中的 import 语句上方添加以下内容。
package com.mongodb.drivers;
以下查询搜索以 2
开头的某个时间列出的属性,并允许以 1
开头的住宿天数。
1 import java.util.Arrays; 2 import static com.mongodb.client.model.Filters.eq; 3 import static com.mongodb.client.model.Aggregates.limit; 4 import static com.mongodb.client.model.Aggregates.project; 5 import static com.mongodb.client.model.Projections.excludeId; 6 import static com.mongodb.client.model.Projections.fields; 7 import com.mongodb.client.MongoClient; 8 import com.mongodb.client.MongoClients; 9 import com.mongodb.client.MongoCollection; 10 import com.mongodb.client.MongoDatabase; 11 import org.bson.Document; 12 13 public class DateNumberToStringQuery { 14 public static void main( String[] args ) { 15 // define query 16 Document agg = new Document("$search", 17 new Document ("index", "date-number-fields-tutorial") 18 .append("compound", 19 new Document("should", Arrays.asList( 20 new Document("autocomplete", 21 new Document("path", "lastScrapedDate") 22 .append("query", "2")), 23 new Document("autocomplete", 24 new Document("path", "maximumNumberOfNights") 25 .append("query", "1")))))); 26 27 // specify connection 28 String uri = "<connection-string>"; 29 30 // establish connection and set namespace 31 try (MongoClient mongoClient = MongoClients.create(uri)) { 32 MongoDatabase database = mongoClient.getDatabase("sample_airbnb"); 33 MongoCollection<Document> collection = database.getCollection("airbnb_mat_view"); 34 // run query and print results 35 collection.aggregate(Arrays.asList( 36 eq("$search", eq("compound", agg)), 37 limit(5), 38 project(fields(excludeId()) )) 39 ).forEach(doc -> System.out.println(doc.toJson())); 40 } 41 } 42 }
在运行示例之前,请将 <connection-string>
替换为 Atlas 连接字符串。确保您的连接字符串包含数据库用户的档案。要了解详情,请参阅通过驱动程序连接。
以下查询会搜索那些住宿天数以 3
开头并且能够容纳以 2
开头的人数的酒店。
1 import java.util.Arrays; 2 import static com.mongodb.client.model.Filters.eq; 3 import static com.mongodb.client.model.Aggregates.limit; 4 import static com.mongodb.client.model.Aggregates.project; 5 import static com.mongodb.client.model.Projections.excludeId; 6 import static com.mongodb.client.model.Projections.fields; 7 import com.mongodb.client.MongoClient; 8 import com.mongodb.client.MongoClients; 9 import com.mongodb.client.MongoCollection; 10 import com.mongodb.client.MongoDatabase; 11 import org.bson.Document; 12 13 public class DateNumberToStringQuery { 14 public static void main( String[] args ) { 15 // define query 16 Document agg = new Document("$search", 17 new Document ("index", "date-number-fields-tutorial") 18 .append("compound", 19 new Document("should", Arrays.asList( 20 new Document("autocomplete", 21 new Document("path", "maximumNumberOfNights") 22 .append("query", "3")), 23 new Document("autocomplete", 24 new Document("path", "accommodatesNumber") 25 .append("query", "2")))))); 26 27 // specify connection 28 String uri = "<connection-string>"; 29 30 // establish connection and set namespace 31 try (MongoClient mongoClient = MongoClients.create(uri)) { 32 MongoDatabase database = mongoClient.getDatabase("sample_airbnb"); 33 MongoCollection<Document> collection = database.getCollection("airbnb_mat_view"); 34 // run query and print results 35 collection.aggregate(Arrays.asList( 36 eq("$search", eq("compound", agg)), 37 limit(5), 38 project(fields(excludeId()) )) 39 ).forEach(doc -> System.out.println(doc.toJson())); 40 } 41 } 42 }
在运行示例之前,请将 <connection-string>
替换为 Atlas 连接字符串。确保您的连接字符串包含数据库用户的档案。要了解详情,请参阅通过驱动程序连接。
编译并运行 DateNumberToStringQuery.java
文件。
javac DateNumberToStringQuery.java java DateNumberToStringQuery
1 { 2 "lastScrapedDate": "2019-03-06", 3 "propertyName": "LAHAINA, MAUI! RESORT/CONDO BEACHFRONT!! SLEEPS 4!", 4 "propertyType": "Condominium", 5 "accommodatesNumber": "4", 6 "maximumNumberOfNights": "1125" 7 } 8 { 9 "lastScrapedDate": "2019-03-06", 10 "propertyName": "Makaha Valley Paradise with OceanView", 11 "propertyType": "Condominium", 12 "accommodatesNumber": "4", 13 "maximumNumberOfNights": "180" 14 } 15 { 16 "lastScrapedDate": "2019-03-06", 17 "propertyName": "March 2019 availability! Oceanview on Sugar Beach!", 18 "propertyType": "Condominium", 19 "accommodatesNumber": "4", 20 "maximumNumberOfNights": "1125" 21 } 22 { 23 "lastScrapedDate": "2019-03-06", 24 "propertyName": "Tropical Jungle Oasis", 25 "propertyType": "Condominium", 26 "accommodatesNumber": "4", 27 "maximumNumberOfNights": "1125" 28 } 29 { 30 "lastScrapedDate": "2019-02-11", 31 "propertyName": "Hospede-se com acesso fácil.", 32 "propertyType": "Condominium", 33 "accommodatesNumber": "4", 34 "maximumNumberOfNights": "1125" 35 }
javac DateNumberToStringQuery.java java DateNumberToStringQuery
1 { 2 "lastScrapedDate": "2019-02-11", 3 "propertyName": "2017 , férias no Rio", 4 "propertyType": "House", 5 "accommodatesNumber": "2", 6 "maximumNumberOfNights": "30" 7 } 8 { 9 "lastScrapedDate": "2019-03-07", 10 "propertyName": "Newly renovated home", 11 "propertyType": "House", 12 "accommodatesNumber": "2", 13 "maximumNumberOfNights": "30" 14 } 15 { 16 "lastScrapedDate": "2019-02-18", 17 "propertyName": "Vintage House For Rent", 18 "propertyType": "House", 19 "accommodatesNumber": "2", 20 "maximumNumberOfNights": "30" 21 } 22 { 23 "lastScrapedDate": "2019-02-18", 24 "propertyName": "4floor house in Taksim,Taksimde 4katli müstakil ev", 25 "propertyType": "House", 26 "accommodatesNumber": "2", 27 "maximumNumberOfNights": "30" 28 } 29 { 30 "lastScrapedDate": "2019-02-16", 31 "propertyName": "22 Oporto Guesthouse Cordoaria", 32 "propertyType": "House", 33 "accommodatesNumber": "2", 34 "maximumNumberOfNights": "30" 35 }
javac DateNumberToStringQuery.java java DateNumberToStringQuery
1 { 2 "lastScrapedDate": "2019-02-11", 3 "propertyName": "Horto flat with small garden", 4 "propertyType": "Apartment", 5 "accommodatesNumber": "4", 6 "maximumNumberOfNights": "1125" 7 } 8 { 9 "lastScrapedDate": "2019-03-06", 10 "propertyName": "Private Room in Bushwick", 11 "propertyType": "Apartment", 12 "accommodatesNumber": "1", 13 "maximumNumberOfNights": "1125" 14 } 15 { 16 "lastScrapedDate": "2019-02-11", 17 "propertyName": "Apt Linda Vista Lagoa - Rio", 18 "propertyType": "Apartment", 19 "accommodatesNumber": "2", 20 "maximumNumberOfNights": "1125" 21 } 22 { 23 "lastScrapedDate": "2019-02-18", 24 "propertyName": "Charming Flat in Downtown Moda", 25 "propertyType": "House", 26 "accommodatesNumber": "6", 27 "maximumNumberOfNights": "1125" 28 } 29 { 30 "lastScrapedDate": "2019-02-11", 31 "propertyName": "Catete's Colonial Big Hause Room B", 32 "propertyType": "House", 33 "accommodatesNumber": "8", 34 "maximumNumberOfNights": "1125" 35 }
javac DateNumberToStringQuery.java java DateNumberToStringQuery
1 { 2 "lastScrapedDate": "2019-03-06", 3 "propertyName": "Ocean View Waikiki Marina w/prkg", 4 "propertyType": "Condominium", 5 "accommodatesNumber": "2", 6 "maximumNumberOfNights": "365" 7 } 8 { 9 "lastScrapedDate": "2019-03-07", 10 "propertyName": "New York City - Upper West Side Apt", 11 "propertyType": "Apartment", 12 "accommodatesNumber": "2", 13 "maximumNumberOfNights": "360" 14 } 15 { 16 "lastScrapedDate": "2019-03-07", 17 "propertyName": "Sydney Hyde Park City Apartment (checkin from 6am)", 18 "propertyType": "Apartment", 19 "accommodatesNumber": "2", 20 "maximumNumberOfNights": "30" 21 } 22 { 23 "lastScrapedDate": "2019-03-07", 24 "propertyName": "Private Room (2) in Guest House at Coogee Beach", 25 "propertyType": "House", 26 "accommodatesNumber": "2", 27 "maximumNumberOfNights": "365" 28 } 29 { 30 "lastScrapedDate": "2019-03-06", 31 "propertyName": "~Ao Lele~ Flying Cloud", 32 "propertyType": "Treehouse", 33 "accommodatesNumber": "2", 34 "maximumNumberOfNights": "30" 35 }
将创建索引的操作符代码复制并粘贴到 DateNumberToStringQuery.kt
文件中。
如果创建了使用动态映射的索引,您可以使用 queryString 操作符查询 airbnb_mat_view
集合。如果创建了使用静态映射的索引,您可以使用 autocomplete 操作符查询 airbnb_mat_view
集合。
此代码示例将执行以下任务:
导入
mongodb
包和依赖项。建立与您的 Atlas 集群的连接。
打印与
AggregateFlow
实例中的查询相匹配的文档。
以下查询搜索房产类型为 Apartment
或 Condominium
,可容纳 2
个人并在 2019
中列出的房产。
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 8 fun main() { 9 // establish connection and set namespace 10 val uri = "<connection-string>" 11 val mongoClient = MongoClient.create(uri) 12 val database = mongoClient.getDatabase("sample_airbnb") 13 val collection = database.getCollection<Document>("airbnb_mat_view") 14 15 runBlocking { 16 // define query 17 val agg = Document( 18 "\$search", 19 Document("index", "date-number-fields-tutorial") 20 .append( 21 "queryString", 22 Document("defaultPath", "propertyType") 23 .append( 24 "query", 25 "propertyType: (Apartment OR Condominium) AND accommodatesNumber: 4 AND lastScrapedDate: 2019" 26 ) 27 ) 28 ) 29 30 // run query and print results 31 val resultsFlow = collection.aggregate<Document>( 32 listOf( 33 agg, 34 limit(5), 35 project(fields(excludeId())) 36 ) 37 ) 38 resultsFlow.collect { println(it) } 39 } 40 mongoClient.close() 41 }
在运行示例之前,请将 <connection-string>
替换为 Atlas 连接字符串。确保您的连接字符串包含数据库用户的档案。要了解详情,请参阅通过驱动程序连接。
以下查询搜索房产类型为House
、可容纳2
人、列在2019
中或最多允许住宿晚数30
晚的房产。
1 import com.mongodb.client.model.Aggregates.limit 2 import com.mongodb.client.model.Aggregates.project 3 import com.mongodb.client.model.Projections.excludeId 4 import com.mongodb.client.model.Projections.fields 5 import com.mongodb.kotlin.client.coroutine.MongoClient 6 import kotlinx.coroutines.runBlocking 7 import org.bson.Document 8 9 fun main() { 10 // establish connection and set namespace 11 val uri = "<connection-string>" 12 val mongoClient = MongoClient.create(uri) 13 val database = mongoClient.getDatabase("sample_airbnb") 14 val collection = database.getCollection<Document>("airbnb_mat_view") 15 16 runBlocking { 17 // define query 18 val agg = Document( 19 "\$search", 20 Document("index", "date-number-fields-tutorial") 21 .append( 22 "queryString", 23 Document("defaultPath", "propertyType") 24 .append( 25 "query", 26 "propertyType: House OR accommodatesNumber: 2 OR lastScrapedDate: 2019 OR maximumNumberOfNights: 30" 27 ) 28 ) 29 ) 30 31 // run query and print results 32 val resultsFlow = collection.aggregate<Document>( 33 listOf( 34 agg, 35 limit(5), 36 project(fields(excludeId())) 37 ) 38 ) 39 resultsFlow.collect { println(it) } 40 } 41 mongoClient.close() 42 }
在运行示例之前,请将 <connection-string>
替换为 Atlas 连接字符串。确保您的连接字符串包含数据库用户的档案。要了解详情,请参阅通过驱动程序连接。
此代码示例将执行以下任务:
导入
mongodb
包和依赖项。建立与您的 Atlas 集群的连接。
打印与
AggregateFlow
实例中的查询相匹配的文档。
以下查询搜索以 2
开头的某个时间列出的属性,并允许以 1
开头的住宿天数。
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 8 fun main() { 9 // establish connection and set namespace 10 val uri = "<connection-string>" 11 val mongoClient = MongoClient.create(uri) 12 val database = mongoClient.getDatabase("sample_airbnb") 13 val collection = database.getCollection<Document>("airbnb_mat_view") 14 15 runBlocking { 16 // define query 17 val agg = Document( 18 "\$search", 19 Document("index", "date-number-fields-tutorial") 20 .append( 21 "compound", 22 Document( 23 "should", listOf( 24 Document( 25 "autocomplete", 26 Document("path", "lastScrapedDate") 27 .append("query", "2") 28 ), 29 Document( 30 "autocomplete", 31 Document("path", "maximumNumberOfNights") 32 .append("query", "1") 33 ) 34 ) 35 ) 36 ) 37 ) 38 39 // run query and print results 40 val resultsFlow = collection.aggregate<Document>( 41 listOf( 42 agg, 43 limit(5), 44 project(fields(excludeId())) 45 ) 46 ) 47 resultsFlow.collect { println(it) } 48 } 49 mongoClient.close() 50 }
在运行示例之前,请将 <connection-string>
替换为 Atlas 连接字符串。确保您的连接字符串包含数据库用户的档案。要了解详情,请参阅通过驱动程序连接。
以下查询会搜索那些住宿天数以 3
开头并且能够容纳以 2
开头的人数的酒店。
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 8 fun main() { 9 // establish connection and set namespace 10 val uri = "<connection-string>" 11 val mongoClient = MongoClient.create(uri) 12 val database = mongoClient.getDatabase("sample_airbnb") 13 val collection = database.getCollection<Document>("airbnb_mat_view") 14 15 runBlocking { 16 // define query 17 val agg = Document( 18 "\$search", 19 Document("index", "date-number-fields-tutorial") 20 .append( 21 "compound", 22 Document( 23 "should", listOf( 24 Document( 25 "autocomplete", 26 Document("path", "maximumNumberOfNights") 27 .append("query", "3") 28 ), 29 Document( 30 "autocomplete", 31 Document("path", "accommodatesNumber") 32 .append("query", "2") 33 ) 34 ) 35 ) 36 ) 37 ) 38 39 // run query and print results 40 val resultsFlow = collection.aggregate<Document>( 41 listOf( 42 agg, 43 limit(5), 44 project(fields(excludeId())) 45 ) 46 ) 47 resultsFlow.collect { println(it) } 48 } 49 mongoClient.close() 50 }
在运行示例之前,请将 <connection-string>
替换为 Atlas 连接字符串。确保您的连接字符串包含数据库用户的档案。要了解详情,请参阅通过驱动程序连接。
运行 DateNumberToStringQuery.kt
文件。
当你在 IDE 中运行 DateNumberToStringQuery.kt
程序时,它会打印以下文档:
Document{{lastScrapedDate=2019-03-06, propertyName=Tropical Jungle Oasis, propertyType=Condominium, accommodatesNumber=4, maximumNumberOfNights=1125}} Document{{lastScrapedDate=2019-03-06, propertyName=Honolulu 1 BR/1Bath Condo - Hilton Hawaiian, propertyType=Condominium, accommodatesNumber=4, maximumNumberOfNights=7}} Document{{lastScrapedDate=2019-03-06, propertyName=Beautiful Apt, Tropical Resort, Steps to the Beach, propertyType=Condominium, accommodatesNumber=4, maximumNumberOfNights=45}} Document{{lastScrapedDate=2019-03-06, propertyName=Ocean View in the heart of Waikiki, propertyType=Condominium, accommodatesNumber=4, maximumNumberOfNights=1125}} Document{{lastScrapedDate=2019-03-06, propertyName=Aloha, Kihei Bay Surf, New Pool and BBQ, propertyType=Condominium, accommodatesNumber=4, maximumNumberOfNights=1125}}
当你在 IDE 中运行 DateNumberToStringQuery.kt
程序时,它会打印以下文档:
Document{{lastScrapedDate=2019-03-11, propertyName=This room is perfect for responsible guests, propertyType=House, accommodatesNumber=2, maximumNumberOfNights=30}} Document{{lastScrapedDate=2019-03-06, propertyName=Queen Room at Beautiful Upscale Organic Farm, propertyType=House, accommodatesNumber=2, maximumNumberOfNights=30}} Document{{lastScrapedDate=2019-03-11, propertyName=Incredible space with amazing views, propertyType=House, accommodatesNumber=2, maximumNumberOfNights=30}} Document{{lastScrapedDate=2019-02-16, propertyName=Varanda Porto, propertyType=House, accommodatesNumber=2, maximumNumberOfNights=30}} Document{{lastScrapedDate=2019-03-06, propertyName=Bright, Clean, Quiet, Modern, propertyType=House, accommodatesNumber=2, maximumNumberOfNights=30}}
当你在 IDE 中运行 DateNumberToStringQuery.kt
程序时,它会打印以下文档:
Document{{lastScrapedDate=2019-03-07, propertyName=Deluxe Loft Suite, propertyType=Apartment, accommodatesNumber=4, maximumNumberOfNights=1125}} Document{{lastScrapedDate=2019-03-11, propertyName=3 chambres au coeur du Plateau, propertyType=Apartment, accommodatesNumber=6, maximumNumberOfNights=1125}} Document{{lastScrapedDate=2019-02-16, propertyName=Be Happy in Porto, propertyType=Loft, accommodatesNumber=2, maximumNumberOfNights=1125}} Document{{lastScrapedDate=2019-02-18, propertyName=Cozy house at Beyoğlu, propertyType=Apartment, accommodatesNumber=2, maximumNumberOfNights=1125}} Document{{lastScrapedDate=2019-02-16, propertyName=Downtown Oporto Inn (room cleaning), propertyType=Hostel, accommodatesNumber=2, maximumNumberOfNights=1125}}
当你在 IDE 中运行 DateNumberToStringQuery.kt
程序时,它会打印以下文档:
Document{{lastScrapedDate=2019-03-06, propertyName=Ocean View Waikiki Marina w/prkg, propertyType=Condominium, accommodatesNumber=2, maximumNumberOfNights=365}} Document{{lastScrapedDate=2019-03-07, propertyName=New York City - Upper West Side Apt, propertyType=Apartment, accommodatesNumber=2, maximumNumberOfNights=360}} Document{{lastScrapedDate=2019-03-06, propertyName=~Ao Lele~ Flying Cloud, propertyType=Treehouse, accommodatesNumber=2, maximumNumberOfNights=30}} Document{{lastScrapedDate=2019-03-06, propertyName=Banyan Bungalow, propertyType=Bungalow, accommodatesNumber=2, maximumNumberOfNights=300}} Document{{lastScrapedDate=2019-03-06, propertyName=Luxury 1-Bdrm in Downtown Brooklyn, propertyType=Apartment, accommodatesNumber=2, maximumNumberOfNights=30}}
将创建索引的操作符代码复制并粘贴到 date-number-to-string-query.js
文件中。
如果创建了使用动态映射的索引,您可以使用 queryString 操作符查询 airbnb_mat_view
集合。如果创建了使用静态映射的索引,您可以使用 autocomplete 操作符查询 airbnb_mat_view
集合。
此代码示例将执行以下任务:
导入
mongodb
,即 MongoDB 的Node.js
驱动程序。创建 MongoClient 类的实例以建立与 Atlas 集群的连接。
遍历游标以打印与查询匹配的文档。
以下查询搜索房产类型为 Apartment
或 Condominium
,可容纳 2
个人并在 2019
中列出的房产。
1 const MongoClient = require("mongodb").MongoClient; 2 const assert = require("assert"); 3 4 const agg = [ 5 { 6 '$search': { 7 'index': 'date-number-fields-tutorial', 8 'queryString': { 9 'defaultPath': 'propertyType', 10 'query': 'propertyType: (Apartment OR Condominium) AND accommodatesNumber: 4 AND lastScrapedDate: 2019' 11 } 12 } 13 }, { 14 '$limit': 5 15 }, { 16 '$project': { 17 '_id': 0 18 } 19 } 20 ]; 21 22 MongoClient.connect( 23 "<connection-string>", 24 { useNewUrlParser: true, useUnifiedTopology: true }, 25 async function (connectErr, client) { 26 assert.equal(null, connectErr); 27 const coll = client.db("sample_airbnb").collection("airbnb_mat_view"); 28 let cursor = await coll.aggregate(agg); 29 await cursor.forEach((doc) => console.log(doc)); 30 client.close(); 31 } 32 );
在运行示例之前,请将 <connection-string>
替换为 Atlas 连接字符串。确保您的连接字符串包含数据库用户的档案。要了解详情,请参阅通过驱动程序连接。
以下查询搜索房产类型为House
、可容纳2
人、列在2019
中或最多允许住宿晚数30
晚的房产。
1 const MongoClient = require("mongodb").MongoClient; 2 const assert = require("assert"); 3 4 const agg = [ 5 { 6 '$search': { 7 'index': 'date-number-fields-tutorial', 8 'queryString': { 9 'defaultPath': 'propertyType', 10 'query': 'propertyType: House OR accommodatesNumber: 2 OR lastScrapedDate: 2019 OR maximumNumberOfNights: 30' 11 } 12 } 13 }, { 14 '$limit': 5 15 }, { 16 '$project': { 17 '_id': 0 18 } 19 } 20 ]; 21 22 MongoClient.connect( 23 "<connection-string>", 24 { useNewUrlParser: true, useUnifiedTopology: true }, 25 async function (connectErr, client) { 26 assert.equal(null, connectErr); 27 const coll = client.db("sample_airbnb").collection("airbnb_mat_view"); 28 let cursor = await coll.aggregate(agg); 29 await cursor.forEach((doc) => console.log(doc)); 30 client.close(); 31 } 32 );
在运行示例之前,请将 <connection-string>
替换为 Atlas 连接字符串。确保您的连接字符串包含数据库用户的档案。要了解详情,请参阅通过驱动程序连接。
此代码示例将执行以下任务:
导入
mongodb
,即 MongoDB 的Node.js
驱动程序。创建 MongoClient 类的实例以建立与 Atlas 集群的连接。
遍历游标以打印与查询匹配的文档。
以下查询搜索以 2
开头的某个时间列出的属性,并允许以 1
开头的住宿天数。
1 const MongoClient = require("mongodb").MongoClient; 2 const assert = require("assert"); 3 4 const agg = [ 5 { 6 '$search': { 7 'index': 'date-number-fields-tutorial', 8 'compound': { 9 'should': [ 10 { 11 'autocomplete': { 12 'path': 'lastScrapedDate', 13 'query': '2' 14 } 15 }, { 16 'autocomplete': { 17 'path': 'maximumNumberOfNights', 18 'query': '1' 19 } 20 } 21 ] 22 } 23 } 24 }, { 25 '$limit': 5 26 }, { 27 '$project': { 28 '_id': 0 29 } 30 } 31 ]; 32 33 MongoClient.connect( 34 "<connection-string>", 35 { useNewUrlParser: true, useUnifiedTopology: true }, 36 async function (connectErr, client) { 37 assert.equal(null, connectErr); 38 const coll = client.db("sample_airbnb").collection("airbnb_mat_view"); 39 let cursor = await coll.aggregate(agg); 40 await cursor.forEach((doc) => console.log(doc)); 41 client.close(); 42 } 43 );
在运行示例之前,请将 <connection-string>
替换为 Atlas 连接字符串。确保您的连接字符串包含数据库用户的档案。要了解详情,请参阅通过驱动程序连接。
以下查询会搜索那些住宿天数以 3
开头并且能够容纳以 2
开头的人数的酒店。
1 const MongoClient = require("mongodb").MongoClient; 2 const assert = require("assert"); 3 4 const agg = [ 5 { 6 '$search': { 7 'index': 'date-number-fields-tutorial', 8 'compound': { 9 'should': [ 10 { 11 'autocomplete': { 12 'path': 'maximumNumberOfNights', 13 'query': '3' 14 } 15 }, { 16 'autocomplete': { 17 'path': 'accommodatesNumber', 18 'query': '2' 19 } 20 } 21 ] 22 } 23 } 24 }, { 25 '$limit': 5 26 }, { 27 '$project': { 28 '_id': 0 29 } 30 } 31 ]; 32 33 MongoClient.connect( 34 "<connection-string>", 35 { useNewUrlParser: true, useUnifiedTopology: true }, 36 async function (connectErr, client) { 37 assert.equal(null, connectErr); 38 const coll = client.db("sample_airbnb").collection("airbnb_mat_view"); 39 let cursor = await coll.aggregate(agg); 40 await cursor.forEach((doc) => console.log(doc)); 41 client.close(); 42 } 43 );
在运行示例之前,请将 <connection-string>
替换为 Atlas 连接字符串。确保您的连接字符串包含数据库用户的档案。要了解详情,请参阅通过驱动程序连接。
运行以下命令来查询您的集合:
node date-number-to-string-query.js
1 { 2 lastScrapedDate: '2019-03-06', 3 propertyName: 'LAHAINA, MAUI! RESORT/CONDO BEACHFRONT!! SLEEPS 4!', 4 propertyType: 'Condominium', 5 accommodatesNumber: '4', 6 maximumNumberOfNights: '1125' 7 } 8 { 9 lastScrapedDate: '2019-03-06', 10 propertyName: 'Makaha Valley Paradise with OceanView', 11 propertyType: 'Condominium', 12 accommodatesNumber: '4', 13 maximumNumberOfNights: '180' 14 } 15 { 16 lastScrapedDate: '2019-03-06', 17 propertyName: 'March 2019 availability! Oceanview on Sugar Beach!', 18 propertyType: 'Condominium', 19 accommodatesNumber: '4', 20 maximumNumberOfNights: '1125' 21 } 22 { 23 lastScrapedDate: '2019-03-06', 24 propertyName: 'Tropical Jungle Oasis', 25 propertyType: 'Condominium', 26 accommodatesNumber: '4', 27 maximumNumberOfNights: '1125' 28 } 29 { 30 lastScrapedDate: '2019-02-11', 31 propertyName: 'Hospede-se com acesso fácil.', 32 propertyType: 'Condominium', 33 accommodatesNumber: '4', 34 maximumNumberOfNights: '1125' 35 } 36
node date-number-to-string-query.js
1 { 2 lastScrapedDate: '2019-02-11', 3 propertyName: '2017 , férias no Rio', 4 propertyType: 'House', 5 accommodatesNumber: '2', 6 maximumNumberOfNights: '30' 7 } 8 { 9 lastScrapedDate: '2019-03-07', 10 propertyName: 'Newly renovated home', 11 propertyType: 'House', 12 accommodatesNumber: '2', 13 maximumNumberOfNights: '30' 14 } 15 { 16 lastScrapedDate: '2019-02-18', 17 propertyName: 'Vintage House For Rent', 18 propertyType: 'House', 19 accommodatesNumber: '2', 20 maximumNumberOfNights: '30' 21 } 22 { 23 lastScrapedDate: '2019-02-18', 24 propertyName: '4floor house in Taksim,Taksimde 4katli müstakil ev', 25 propertyType: 'House', 26 accommodatesNumber: '2', 27 maximumNumberOfNights: '30' 28 } 29 { 30 lastScrapedDate: '2019-02-16', 31 propertyName: '22 Oporto Guesthouse Cordoaria', 32 propertyType: 'House', 33 accommodatesNumber: '2', 34 maximumNumberOfNights: '30' 35 }
node date-number-to-string-query.js
1 { 2 lastScrapedDate: '2019-02-11', 3 propertyName: 'Horto flat with small garden', 4 propertyType: 'Apartment', 5 accommodatesNumber: '4', 6 maximumNumberOfNights: '1125' 7 } 8 { 9 lastScrapedDate: '2019-03-06', 10 propertyName: 'Private Room in Bushwick', 11 propertyType: 'Apartment', 12 accommodatesNumber: '1', 13 maximumNumberOfNights: '1125' 14 } 15 { 16 lastScrapedDate: '2019-02-11', 17 propertyName: 'Apt Linda Vista Lagoa - Rio', 18 propertyType: 'Apartment', 19 accommodatesNumber: '2', 20 maximumNumberOfNights: '1125' 21 } 22 { 23 lastScrapedDate: '2019-02-18', 24 propertyName: 'Charming Flat in Downtown Moda', 25 propertyType: 'House', 26 accommodatesNumber: '6', 27 maximumNumberOfNights: '1125' 28 } 29 { 30 lastScrapedDate: '2019-02-11', 31 propertyName: "Catete's Colonial Big Hause Room B", 32 propertyType: 'House', 33 accommodatesNumber: '8', 34 maximumNumberOfNights: '1125' 35 }
node date-number-to-string-query.js
1 { 2 lastScrapedDate: '2019-03-06', 3 propertyName: 'Ocean View Waikiki Marina w/prkg', 4 propertyType: 'Condominium', 5 accommodatesNumber: '2', 6 maximumNumberOfNights: '365' 7 } 8 { 9 lastScrapedDate: '2019-03-07', 10 propertyName: 'New York City - Upper West Side Apt', 11 propertyType: 'Apartment', 12 accommodatesNumber: '2', 13 maximumNumberOfNights: '360' 14 } 15 { 16 lastScrapedDate: '2019-03-07', 17 propertyName: 'Sydney Hyde Park City Apartment (checkin from 6am)', 18 propertyType: 'Apartment', 19 accommodatesNumber: '2', 20 maximumNumberOfNights: '30' 21 } 22 { 23 lastScrapedDate: '2019-03-07', 24 propertyName: 'Private Room (2) in Guest House at Coogee Beach', 25 propertyType: 'House', 26 accommodatesNumber: '2', 27 maximumNumberOfNights: '365' 28 } 29 { 30 lastScrapedDate: '2019-03-06', 31 propertyName: '~Ao Lele~ Flying Cloud', 32 propertyType: 'Treehouse', 33 accommodatesNumber: '2', 34 maximumNumberOfNights: '30' 35 }
将创建索引的操作符的代码示例复制并粘贴到 date-number-to-string-query.py
文件中。
如果创建了使用动态映射的索引,您可以使用 queryString 操作符查询 airbnb_mat_view
集合。如果创建了使用静态映射的索引,您可以使用 autocomplete 操作符查询 airbnb_mat_view
集合。
此代码示例将执行以下任务:
导入
pymongo
、MongoDB 的 Python 驱动程序和dns
模块,这是使用 DNS 种子列表连接字符串将pymongo
连接到Atlas
所必需的。创建一个
MongoClient
类实例,以建立与 Atlas 集群的连接。遍历游标以打印与查询匹配的文档。
以下查询搜索房产类型为 Apartment
或 Condominium
,可容纳 2
个人并在 2019
中列出的房产。
1 import pymongo 2 import dns 3 4 client = pymongo.MongoClient('<connection-string>') 5 result = client['sample_airbnb']['airbnb_mat_view'].aggregate([ 6 { 7 '$search': { 8 'index': 'date-number-fields-tutorial', 9 'queryString': { 10 'defaultPath': 'propertyType', 11 'query': 'propertyType: (Apartment OR Condominium) AND accommodatesNumber: 4 AND lastScrapedDate: 2019' 12 } 13 } 14 }, { 15 '$limit': 5 16 }, { 17 '$project': { 18 '_id': 0 19 } 20 } 21 ]) 22 23 for i in result: 24 print(i)
在运行示例之前,请将 <connection-string>
替换为 Atlas 连接字符串。确保您的连接字符串包含数据库用户的档案。要了解详情,请参阅通过驱动程序连接。
以下查询搜索房产类型为House
、可容纳2
人、列在2019
中或最多允许住宿晚数30
晚的房产。
1 import pymongo 2 import dns 3 4 client = pymongo.MongoClient('<connection-string>') 5 result = client['sample_airbnb']['airbnb_mat_view'].aggregate([ 6 { 7 '$search': { 8 'index': 'date-number-fields-tutorial', 9 'queryString': { 10 'defaultPath': 'propertyType', 11 'query': 'propertyType: House OR accommodatesNumber: 2 OR lastScrapedDate: 2019 OR maximumNumberOfNights: 30' 12 } 13 } 14 }, { 15 '$limit': 5 16 }, { 17 '$project': { 18 '_id': 0 19 } 20 } 21 ]) 22 23 for i in result: 24 print(i)
在运行示例之前,请将 <connection-string>
替换为 Atlas 连接字符串。确保您的连接字符串包含数据库用户的档案。要了解详情,请参阅通过驱动程序连接。
此代码示例将执行以下任务:
导入
pymongo
、MongoDB 的 Python 驱动程序和dns
模块,这是使用 DNS 种子列表连接字符串将pymongo
连接到Atlas
所必需的。创建一个
MongoClient
类实例,以建立与 Atlas 集群的连接。遍历游标以打印与查询匹配的文档。
以下查询搜索以 2
开头的某个时间列出的属性,并允许以 1
开头的住宿天数。
1 import pymongo 2 import dns 3 4 client = pymongo.MongoClient('<connection-string>') 5 result = client['sample_airbnb']['airbnb_mat_view'].aggregate([ 6 { 7 '$search': { 8 'index': 'date-number-fields-tutorial', 9 'compound': { 10 'should': [ 11 { 12 'autocomplete': { 13 'path': 'lastScrapedDate', 14 'query': '2' 15 } 16 }, { 17 'autocomplete': { 18 'path': 'maximumNumberOfNights', 19 'query': '1' 20 } 21 } 22 ] 23 } 24 } 25 }, { 26 '$limit': 5 27 }, { 28 '$project': { 29 '_id': 0 30 } 31 } 32 ]) 33 34 for i in result: 35 print(i)
在运行示例之前,请将 <connection-string>
替换为 Atlas 连接字符串。确保您的连接字符串包含数据库用户的档案。要了解详情,请参阅通过驱动程序连接。
以下查询会搜索那些住宿天数以 3
开头并且能够容纳以 2
开头的人数的酒店。
1 import pymongo 2 import dns 3 4 client = pymongo.MongoClient('<connection-string>') 5 result = client['sample_airbnb']['airbnb_mat_view'].aggregate([ 6 { 7 '$search': { 8 'index': 'date-number-fields-tutorial', 9 'compound': { 10 'should': [ 11 { 12 'autocomplete': { 13 'path': 'maximumNumberOfNights', 14 'query': '3' 15 } 16 }, { 17 'autocomplete': { 18 'path': 'accommodatesNumber', 19 'query': '2' 20 } 21 } 22 ] 23 } 24 } 25 }, { 26 '$limit': 5 27 }, { 28 '$project': { 29 '_id': 0 30 } 31 } 32 ]) 33 34 for i in result: 35 print(i)
在运行示例之前,请将 <connection-string>
替换为 Atlas 连接字符串。确保您的连接字符串包含数据库用户的档案。要了解详情,请参阅通过驱动程序连接。
运行以下命令来查询您的集合:
python date-number-to-string-query.py
1 { 2 'lastScrapedDate': '2019-03-06', 3 'propertyName': 'LAHAINA, MAUI! RESORT/CONDO BEACHFRONT!! SLEEPS 4!', 4 'propertyType': 'Condominium', 5 'accommodatesNumber': '4', 6 'maximumNumberOfNights': '1125' 7 } 8 { 9 'lastScrapedDate': '2019-03-06', 10 'propertyName': 'Makaha Valley Paradise with OceanView', 11 'propertyType': 'Condominium', 12 'accommodatesNumber': '4', 13 'maximumNumberOfNights': '180' 14 } 15 { 16 'lastScrapedDate': '2019-03-06', 17 'propertyName': 'March 2019 availability! Oceanview on Sugar Beach!', 18 'propertyType': 'Condominium', 19 'accommodatesNumber': '4', 20 'maximumNumberOfNights': '1125' 21 } 22 { 23 'lastScrapedDate': '2019-03-06', 24 'propertyName': 'Tropical Jungle Oasis', 25 'propertyType': 'Condominium', 26 'accommodatesNumber': '4', 27 'maximumNumberOfNights': '1125' 28 } 29 { 30 'lastScrapedDate': '2019-02-11', 31 'propertyName': 'Hospede-se com acesso fácil.', 32 'propertyType': 'Condominium', 33 'accommodatesNumber': '4', 34 'maximumNumberOfNights': '1125' 35 }
python date-number-to-string-query.py
1 { 2 'lastScrapedDate': '2019-02-11', 3 'propertyName': '2017 , férias no Rio', 4 'propertyType': 'House', 5 'accommodatesNumber': '2', 6 'maximumNumberOfNights': '30' 7 } 8 { 9 'lastScrapedDate': '2019-03-07', 10 'propertyName': 'Newly renovated home', 11 'propertyType': 'House', 12 'accommodatesNumber': '2', 13 'maximumNumberOfNights': '30' 14 } 15 { 16 'lastScrapedDate': '2019-02-18', 17 'propertyName': 'Vintage House For Rent', 18 'propertyType': 'House', 19 'accommodatesNumber': '2', 20 'maximumNumberOfNights': '30' 21 } 22 { 23 'lastScrapedDate': '2019-02-18', 24 'propertyName': '4floor house in Taksim,Taksimde 4katli müstakil ev', 25 'propertyType': 'House', 26 'accommodatesNumber': '2', 27 'maximumNumberOfNights': '30' 28 } 29 { 30 'lastScrapedDate': '2019-02-16', 31 'propertyName': '22 Oporto Guesthouse Cordoaria', 32 'propertyType': 'House', 33 'accommodatesNumber': '2', 34 'maximumNumberOfNights': '30' 35 }
python date-number-to-string-query.py
1 { 2 'lastScrapedDate': '2019-02-11', 3 'propertyName': 'Horto flat with small garden', 4 'propertyType': 'Apartment', 5 'accommodatesNumber': '4', 6 'maximumNumberOfNights': '1125' 7 } 8 { 9 'lastScrapedDate': '2019-03-06', 10 'propertyName': 'Private Room in Bushwick', 11 'propertyType': 'Apartment', 12 'accommodatesNumber': '1', 13 'maximumNumberOfNights': '1125' 14 } 15 { 16 'lastScrapedDate': '2019-02-11', 17 'propertyName': 'Apt Linda Vista Lagoa - Rio', 18 'propertyType': 'Apartment', 19 'accommodatesNumber': '2', 20 'maximumNumberOfNights': '1125' 21 } 22 { 23 'lastScrapedDate': '2019-02-18', 24 'propertyName': 'Charming Flat in Downtown Moda', 25 'propertyType': 'House', 26 'accommodatesNumber': '6', 27 'maximumNumberOfNights': '1125' 28 } 29 { 30 'lastScrapedDate': '2019-02-11', 31 'propertyName': "Catete's Colonial Big Hause Room B", 32 'propertyType': 'House', 33 'accommodatesNumber': '8', 34 'maximumNumberOfNights': '1125' 35 }
python date-number-to-string-query.py
1 { 2 'lastScrapedDate': '2019-03-06', 3 'propertyName': 'Ocean View Waikiki Marina w/prkg', 4 'propertyType': 'Condominium', 5 'accommodatesNumber': '2', 6 'maximumNumberOfNights': '365' 7 } 8 { 9 'lastScrapedDate': '2019-03-07', 10 'propertyName': 'New York City - Upper West Side Apt', 11 'propertyType': 'Apartment', 12 'accommodatesNumber': '2', 13 'maximumNumberOfNights': '360' 14 } 15 { 16 'lastScrapedDate': '2019-03-07', 17 'propertyName': 'Sydney Hyde Park City Apartment (checkin from 6am)', 18 'propertyType': 'Apartment', 19 'accommodatesNumber': '2', 20 'maximumNumberOfNights': '30' 21 } 22 { 23 'lastScrapedDate': '2019-03-07', 24 'propertyName': 'Private Room (2) in Guest House at Coogee Beach', 25 'propertyType': 'House', 26 'accommodatesNumber': '2', 27 'maximumNumberOfNights': '365' 28 } 29 { 30 'lastScrapedDate': '2019-03-06', 31 'propertyName': '~Ao Lele~ Flying Cloud', 32 'propertyType': 'Treehouse', 33 'accommodatesNumber': '2', 34 'maximumNumberOfNights': '30' 35 }