Overview
在此页面上,您可以查看可复制的代码示例,这些示例展示了使用PyMongo查找文档的常用方法。
提示
要了解有关此页面上显示的任何方法的更多信息,请参阅每个部分中提供的链接。
要使用此页面中的示例,请将代码示例复制到示例应用程序或您自己的应用程序中。 请务必将代码示例中的所有占位符(例如<connection string URI> )替换为 MongoDB 部署的相关值。
示例应用程序
您可以使用以下示例应用程序来测试本页上的代码示例。 要使用示例应用程序,请执行以下步骤:
确保已安装 PyMongo。
复制以下代码并将其粘贴到新的
.py文件中。从此页面复制代码示例,并将其粘贴到文件中的指定行。
选择 Synchronous 或 Asynchronous标签页,查看相应的代码:
import pymongofrom pymongo import MongoClient
try: uri = "<connection string URI>" client = MongoClient(uri)
database = client["<database name>"] collection = database["<collection name>"]
# start example code here
# end example code here
client.close()
except Exception as e: raise Exception( "The following error occurred: ", e)import asyncioimport pymongofrom pymongo import AsyncMongoClient
async def main(): try: uri = "<connection string URI>" client = AsyncMongoClient(uri)
database = client["<database name>"] collection = database["<collection name>"]
# start example code here
# end example code here
await client.close()
except Exception as e: raise Exception( "The following error occurred: ", e)
asyncio.run(main())查找一个
results = collection.find_one({ "<field name>" : "<value>" })
print(results)results = await collection.find_one({ "<field name>" : "<value>" })
print(results)要了解有关find_one()方法的更多信息,请参阅“检索数据”指南中的“查找一个文档”。
查找多个
results = collection.find({ "<field name>" : "<value>" })
for document in results: print(document)results = collection.find({ "<field name>" : "<value>" })
async for document in results: print(document)要了解有关find()方法的更多信息,请参阅检索数据指南中的查找多个文档。
对集合中的文档进行计数
count = collection.count_documents({})
print(count)count = await collection.count_documents({})
print(count)要了解有关count_documents()方法的更多信息,请参阅《检索准确计数》指南。
对查询返回的文档进行计数
count = collection.count_documents({ "<field name>": "<value>" })
print(count)count = await collection.count_documents({ "<field name>": "<value>" })
print(count)要了解有关count_documents()方法的更多信息,请参阅《检索准确计数》指南。
估计文档计数
count = collection.estimated_document_count()
print(count)count = await collection.estimated_document_count()
print(count)要了解有关estimated_document_count()方法的更多信息,请参阅“检索估计计数”指南。
Retrieve Distinct Values
results = collection.distinct("<field name>")
for document in results: print(document)results = await collection.distinct("<field name>")
for document in results: print(document)要了解有关distinct()方法的更多信息,请参阅“检索不同字段值”指南。
监控数据变化
with collection.watch() as stream: for change in stream: print(change)async with await collection.watch() as stream: async for change in stream: print(change)要学习;了解有关 watch() 方法的更多信息,请参阅《使用变更流监控数据》指南。