Overview
在本指南中,您可以学习如何使用Ruby驱动程序检索集合中指定字段的不同值。
在集合中,文档中的单个字段可能包含不同的值。示例,restaurants集合中一个文档的borough 值为 'Manhattan',而另一文档的 borough 值为 'Queens'。您可以使用Ruby驱动程序检索集合中多个文档中某个字段包含的所有唯一值。
样本数据
本指南中的示例使用 Atlas示例数据集的 sample_restaurants数据库中的 restaurants集合。要从Ruby应用程序访问权限此集合,请创建一个连接到Atlas 集群的Mongo::Client对象,并将以下值分配给 database 和 collection 变量:
database = client.use('sample_restaurants') collection = database[:restaurants]
要学习;了解如何创建免费的MongoDB Atlas 群集并加载示例数据集,请参阅MongoDB入门指南。
Retrieve Distinct Values
要检索指定字段的非重复值,请调用distinct方法并传入要查找非重复值的字段的名称。
检索集合中的值
以下示例检索restaurants集合中borough字段的非重复值:
results = collection.distinct('borough') results.each do |value| puts value end
Bronx Brooklyn Manhattan Missing Queens Staten Island
该操作返回一个大量,用于存储每个不同的borough字段值。 尽管多个文档在borough字段中具有相同的值,但每个值仅在结果中出现一次。
检索指定文档中的值
您可以为 distinct 方法提供查询过滤,以查找集合中文档子集的不同字段值。查询过滤是一个表达式,用于指定在操作中匹配文档的搜索条件。
提示
要了解有关创建查询过滤的更多信息,请参阅《指定查询》指南。
以下示例检索cuisine字段值为'Italian'的所有文档的borough字段的非重复值:
results = collection.distinct('borough', { cuisine: 'Italian' }) results.each do |value| puts value end
Bronx Brooklyn Manhattan Queens Staten Island
修改不同行为
您可以通过传递指定选项值的 Hash对象来修改 distinct 方法的行为。下表描述了可设立用于自定义操作的选项:
选项 | 说明 |
|---|---|
| The collation to use for the operation. Type: Hash |
| The maximum amount of time in milliseconds that the operation can run. Type: Integer |
| The read preference to use for the operation. To learn more, see
Read Preference in the MongoDB Server manual. Type: Hash |
| The session to use for the operation. Type: Session |
以下示例检索 borough字段值为 'Bronx' 且 cuisine字段值为 'Pizza' 的所有文档的 name字段的非重复值。它还设置 read 选项,指示操作使用 primary_preferred读取偏好(read preference):
filter = { borough: 'Bronx', cuisine: 'Pizza' } options = { read: { mode: :primary_preferred } } results = collection.distinct('name', filter, options) results.each do |value| puts value end
$1.25 Pizza 18 East Gunhill Pizza 2 Bros Aenos Pizza Alitalia Pizza Restaurant Amici Pizza And Pasta Angie'S Cafe Pizza Anthony & Joe'S Pizza Anthony'S Pizza Antivari Pizza Arturo'S Pizza Bartow Pizza ...
API 文档
要学习;了解有关 distinct 方法的详情,请参阅API文档。