首页 > 解决方案 > 从 Pymongo 游标读取 101 个对象立即运行——从 Pymongo 游标读取 102 个对象挂起

问题描述

我对这种行为有点迷惑。我有一个 Pymongo 查询,它从集合中的所有记录中获取一个字段(该集合包含 100 万条记录):

from pymongo import MongoClient

client = MongoClient()
db = client.holidays

serials = db.christmas.find({}, {
  '_id': 0,
  'gifts': 1, # this field is an integer
})

然后,我将这个字典生成器(每个都有一个键)转换为gifts具有以下内容的值列表,该列表立即运行:

l = []
for idx, i in enumerate(serials):
  l.append(i['gifts'])
  if idx > 99: break

但是,如果我将最后一行更改为if idx > 100: break,则该过程将挂起并且永远不会返回。有谁知道可能导致这种行为的原因?欢迎所有建议!

标签: pythonmongodbpymongo

解决方案


无论出于何种原因,我都无法重现您的问题。也许是版本问题(我是 python 3.8.5;pymongo 3.11.0,mongodb 4.2.10)。我加载了一个包含 1M(尽管很小)文档的样本集合,并且在一台普通的 PC 上完成了不到 2.5 秒。如果你得到不同的结果,也许尝试升级。

from pymongo import MongoClient
import datetime

db = MongoClient()['mydatabase']

# Uncomment the next line to load the sample data
# db.mycollection.insert_many([{'gifts': x} for x in range(1000000)]) 

start_time = datetime.datetime.now()

l = [x['gifts'] for x in db.mycollection.find({}, {'_id': 0, 'gifts': 1})]

print(f'{(datetime.datetime.now() - start_time).total_seconds()} Seconds')
print(len(l))

印刷:

2.383489 Seconds
1000000

推荐阅读