Docs 菜单
Docs 主页
/ / /
pymongo
/

Retrieve Data

在此页面上

  • Overview
  • 样本数据
  • 查找文档
  • 查找一个文档
  • 查找多个文档
  • 修改查找行为
  • 更多信息
  • API 文档

在本指南中,您可以了解如何使用 PyMongo(MongoDB 同步 Python 驱动程序)通过读取操作从 MongoDB 集合中检索数据。 您可以调用 find()find_one()方法来检索与一组条件匹配的文档。

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

PyMongo 包含两种从集合中检索文档的方法: find_one()find() 。 这些方法采用查询筛选器并返回一个或多个匹配的文档。 查询筛选器是一个对象,用于指定要在查询中检索的文档。

如需了解有关查询过滤器的更多信息,请参阅指定查询

要查找集合中的单个文档,请调用find_one()方法并传递查询筛选器,其中指定要查找的文档条件。 如果有多个文档与查询筛选器匹配,则此方法会以 Python 字典的形式从检索到的结果中返回第一个匹配的文档。 如果没有与查询筛选器匹配的文档,该方法将返回None

提示

当您知道只有一个匹配文档或者您只对第一个匹配项感兴趣时, find_one()方法非常有用。

以下示例使用find_one()方法查找"cuisine"字段值为"Bakery"的第一个文档:

restaurant = sample_restaurants.restaurants.find_one({"cuisine": "Bakery"})

提示

排序顺序

如果未指定排序条件, find_one()方法会按自然顺序返回磁盘上的第一个文档。

要了解有关排序的更多信息,请参阅排序指南。

要查找集合中的多个文档,请将查询筛选器传递给 find() 方法,其中指定要检索的文档条件。

以下示例使用find()方法查找"cuisine"字段值为"Spanish"的所有文档:

cursor = sample_restaurants.restaurants.find({"cuisine": "Spanish"})

您可以使用游标迭代 find() 方法返回的文档。游标机制允许应用程序迭代数据库结果,同时在给定时间仅将数据库结果的子集保留在内存中。当 find() 方法返回大量文档时,游标非常有用。

您可以使用for-in循环遍历游标中的文档,如以下示例所示:

cursor = sample_restaurants.restaurants.find({"cuisine": "Spanish"})
for restaurant in cursor:
...

注意

查找所有文档

要查找集合中的所有文档,请将空筛选器传递给find()方法:

all_restaurants = sample_restaurants.restaurants.find({})

您可以通过向find()find_one()方法传递命名参数来修改它们的行为。 下表描述了常用参数:

Argument
说明
batch_size
Limits the number of documents to hold in a cursor at a given time.
collation
An instance of the Collation class that sets the collation options.
comment
A string to attach to the query. This can help you trace and interpret the operation in the server logs and in profile data. To learn more about query comments, see the $comment page.
hint
The index to use for the query.
max_time_ms
The maximum execution time on the server for this operation. If this time is exceeded, PyMongo aborts the operation and raises an ExecutionTimeout.

以下示例使用find()方法查找"cuisine"字段值为"Italian"的所有文档,并将最长执行时间设置为10秒( 10 , 000毫秒):

cursor = sample_restaurants.restaurants.find({"cuisine": "Italian"}, max_time_ms=10000)

有关可用参数的完整列表,请参阅 API 文档find() method

如需了解有关查询过滤器的更多信息,请参阅指定查询

有关使用 PyMongo 检索文档的可运行代码示例,请参阅从 MongoDB 读取数据。

要进一步了解本指南所讨论的任何方法或类型,请参阅以下 API 文档:

后退

指定查询