文档菜单

文档首页开发应用程序Python 驱动PyMongo

检索不同的字段值

本页内容

  • 概述
  • 示例数据
  • distinct() 方法
  • 检索集合中的不同值
  • 检索指定文档中的不同值
  • 修改distinct行为
  • API 文档

在集合中,不同的文档可能包含同一字段的不同值。例如,一个restaurant 文档的 borough 值为 "Manhattan",另一个的值为 "Queens"。使用PyMongo,您可以检索集合中多个文档中字段的全部不同值。

本指南中的示例使用来自Atlas 示例数据集sample_restaurants.restaurants 集合。有关如何创建免费MongoDB Atlas集群并加载示例数据集的信息,请参阅PyMongo 入门。

要获取指定字段的唯一值,请调用 distinct() 方法,并传入您想获取唯一值的字段名称。

以下示例检索 restaurants 集合中 borough 字段的唯一值。

results = restaurants.distinct("borough")
for restaurant in results:
print(restaurant)
Bronx
Brooklyn
Manhattan
Missing
Queens
Staten Island

结果显示了集合中所有文档的 borough 字段中出现的每个唯一值。尽管多个文档在 borough 字段中具有相同的值,但每个值在结果中只出现一次。

您可以将 查询过滤器 传递给 distinct() 方法,以检索集合中子集文档的唯一字段值。查询过滤器是一个表达式,用于指定用于匹配操作中文档的搜索条件。有关创建查询过滤器的更多信息,请参阅 指定查询。

以下示例检索所有具有 cuisine 字段值为 "Italian" 的文档的 borough 字段的唯一值。

results = restaurants.distinct("borough", {
"cuisine": "Italian"
})
for restaurant in results:
print(restaurant)
Bronx
Brooklyn
Manhattan
Queens
Staten Island

distinct() 方法接受可选参数,这些参数表示您可以使用它们来配置操作的选项。如果您不指定任何选项,驱动程序不会自定义操作。

以下表格描述了您可以设置以自定义 distinct() 的选项

属性
描述
filter
一个查询过滤器,用于指定从哪些文档中检索唯一值。
session
ClientSession 的一个实例。
comment
要附加到操作的注释。
maxTimeMS
允许操作运行的最大时间,以毫秒为单位。
collation
Collation 的一个实例。

以下示例检索所有具有 borough 字段值为 "Bronx"cuisine 字段值为 "Pizza" 的文档的 name 字段的唯一值。它还使用 comment 选项向操作添加注释。

results = restaurants.distinct("name",
{ "borough": "Bronx",
"cuisine": "Pizza" },
comment="Bronx pizza restaurants"
)
$1.25 Pizza
18 East Gunhill Pizza
2 Bros
Aenos Pizza
Alitalia Pizza Restaurant
...

要了解更多关于本指南中讨论的任何方法或类型,请参阅以下API文档

← 计数文档