python 多线程读取mongo
以下是Python多线程读取MongoDB的示例代码:
import pymongo
import threading
# 创建MongoDB客户端
client = pymongo.MongoClient("mongodb://localhost:27017/")
# 获取数据库和集合对象
db = client["mydatabase"]
col = db["mycollection"]
# 定义线程操作函数
def read_data():
for x in col.find():
print(x)
# 创建多个线程
threads = []
for i in range(5):
t = threading.Thread(target=read_data)
threads.append(t)
# 启动所有线程
for t in threads:
t.start()
# 等待所有线程完成
for t in threads:
t.join()
在此示例中,我们首先创建MongoDB客户端并获取数据库和集合对象。然后,我们定义了一个名为“read_data”的线程操作函数,该函数使用col.find()查询集合中的所有文档并打印它们。接下来,我们创建了5个线程,并将它们添加到一个线程列表中。最后,我们启动所有线程并等待它们完成。由于每个线程都在单独的线程上运行,因此可以同时读取MongoDB中的多个文档
原文地址: http://www.cveoy.top/t/topic/fqmC 著作权归作者所有。请勿转载和采集!