文档菜单

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

从 MongoDB 读取数据

本页内容

  • 概述
  • 示例应用程序
  • 查找一个
  • 查找多个
  • 计算集合中的文档数
  • 计算查询返回的文档数
  • 估计文档数
  • 检索不同值

在本页中,您可以看到可复制的代码示例,展示了您可以使用 PyMongo 检索文档的常用方法。

提示

要了解本页上显示的任何方法,请参阅每个部分中提供的链接。

要使用本页上的示例,请将代码示例复制到示例应用程序或您自己的应用程序中。请确保将代码示例中的所有占位符(如<连接字符串URI>),替换为您 MongoDB 部署的相关值。

您可以使用以下示例应用程序测试本页上的代码示例。要使用示例应用程序,请执行以下步骤

  1. 确保您已安装 PyMongo。

  2. 复制以下代码并将其粘贴到一个新的.py文件中。

  3. 从本页复制一个代码示例并将其粘贴到文件中指定的行。

1import pymongo
2from pymongo import MongoClient
3
4try:
5 uri = "<connection string URI>"
6 client = MongoClient(uri)
7
8 database = client["<database name>"]
9 collection = database["<collection name>"]
10
11 # start example code here
12
13 # end example code here
14
15 client.close()
16
17except Exception as e:
18 raise Exception(
19 "The following error occurred: ", e)
results = collection.find_one({ "<field name>" : "<value>" })
print(results)

要了解更多关于 find_one() 方法的信息,请参阅《检索数据指南》中的查找单个文档

results = collection.find({ "<field name>" : "<value>" })
for document in results:
print(document)

要了解更多关于 find() 方法的知识,请参阅《检索数据指南》中的查找多个文档

count = collection.count_documents({})
print(count)

要了解更多关于 count_documents() 方法的知识,请参阅获取精确计数指南。

count = collection.count_documents({ "<field name>": "<value>" })
print(count)

要了解更多关于 count_documents() 方法的知识,请参阅获取精确计数指南。

count = collection.estimated_document_count()
print(count)

要了解更多关于 estimated_document_count() 方法的知识,请参阅获取估计计数指南。

results = collection.distinct("<field name>")
for document in results:
print(document)

要了解更多关于 distinct() 方法的知识,请参阅检索不同字段值指南。

← 存储大文件