如何使用 pymongo 迭代 MongoDB 集合中的所有文档
此示例将连接到运行在 localhost(默认端口 27017)上的 MongoDB,不带任何用户名或密码,打开名为 mydb 的数据库(另请参阅使用 pymongo 的 Python MongoDB 最小连接示例),打开集合 mycollection 并迭代该集合中的所有文档,打印每个文档。
mongodb_iter_docs.py
from pymongo import MongoClient
client = MongoClient("mongodb://localhost")
db = client["mydb"]
mycollection = db["mycollection"]
for doc in mycollection.find():
print(doc)这将打印,例如,
mongodb_iter_output.py
{'_id': 123, 'name': 'John', 'phone': '+123456789'}If this post helped you, please consider buying me a coffee or donating via PayPal to support research & publishing of new posts on TechOverflow