以下是使用 Python 的 with open 语句读取 MongoDB 数据的示例代码:

import pymongo

# 连接 MongoDB 数据库
client = pymongo.MongoClient('mongodb://localhost:27017/')
db = client['mydatabase']
collection = db['mycollection']

# 使用 with open 读取 MongoDB 数据
with open('data.txt', 'w') as f:
    for doc in collection.find():
        f.write(str(doc) + '
')

在上面的代码中,我们首先使用 pymongo 模块连接到 MongoDB 数据库。然后,我们使用 with open 语句创建一个名为 'data.txt' 的文件,并将每个文档写入文件中。最后,我们在 with 语句块结束时自动关闭文件。

请注意,我们在调用 find() 方法时没有传递任何参数,这意味着我们将检索集合中的所有文档。如果您只想读取特定条件的文档,请在 find() 方法中传递相应的查询条件。

Python 使用 with open 读取 MongoDB 数据

原文地址: https://www.cveoy.top/t/topic/oWXr 著作权归作者所有。请勿转载和采集!

免费AI点我,无需注册和登录