Docs 菜单
Docs 主页
/ / /
Pymongo 驱动程序
/ /

检索不同字段值

在此页面上

  • Overview
  • 样本数据
  • distinct() 方法
  • 检索集合中的不同值
  • 检索指定文档中的不同值
  • 修改不同行为
  • API 文档

在集合中,不同文档的单个字段可能包含不同值。 例如,一个 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

A query filter that specifies the documents to retrieve distinct values from.

session

An instance of ClientSession.

comment

A comment to attach to the operation.

maxTimeMS

The maximum amount of time to allow the operation to run, in milliseconds.

collation

An instance of 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 文档:

后退

计算文档