对于 AI 代理:可在 https://www.mongodb.com/zh-cn/docs/llms.txt 获取文档索引—通过在任何 URL 路径后添加 .md 可获取所有页面的 Markdown 版本。
Docs 菜单

检索不同字段值

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

本指南中的示例使用Atlas示例数据集中sample_restaurants.restaurants集合。 要学习;了解如何创建免费的MongoDB Atlas 群集并加载示例数据集,请参阅PyMongo入门 。

要检索指定字段的非重复值,请调用distinct()方法并传入要查找非重复值的字段的名称。

以下示例检索 restaurants集合中 borough字段的非重复值。选择SynchronousAsynchronous标签页以查看相应的代码:

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

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

您可以为distinct()方法提供查询筛选器,以查找集合中文档子集的不同字段值。 查询筛选器是一个表达式,指定Atlas Search用于匹配操作中的文档的条件。 有关创建查询筛选器的更多信息,请参阅指定查询。

以下示例检索 cuisine字段值为 "Italian" 的所有文档的 borough字段的非重复值。选择SynchronousAsynchronous标签页以查看相应的代码:

results = restaurants.distinct("borough", {
"cuisine": "Italian"
})
for restaurant in results:
print(restaurant)
Bronx
Brooklyn
Manhattan
Queens
Staten Island
results = await 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 选项为操作添加注释。选择SynchronousAsynchronous标签页以查看相应的代码:

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
...
results = await 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 文档: