python - 从 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
,则该过程将挂起并且永远不会返回。有谁知道可能导致这种行为的原因?欢迎所有建议!
解决方案
无论出于何种原因,我都无法重现您的问题。也许是版本问题(我是 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
推荐阅读
- reactjs - 在 docker compose 上运行 create react app - “错误:找不到模块‘react’”
- docker - docker-compose 工作,但 docker run 不
- android - 如果没有 @inject 构造函数或 @Provides - 带注释的方法,则无法提供 Hilt java.lang.Integer
- delphi - Delphi中的计时器事件是否发生在它们自己的线程中?
- java - Gson 使用自定义方法反序列化扩展特定类的嵌套对象
- git - 如何解决我想保留更改并拒绝在最新分支中删除文件的git冲突
- powerbi - 矩阵行的自定义格式
- php - 在 PHP 的 pregmatch 中用粗体版本替换子字符串
- google-apps-script - 使用 Firebase 登录 Google 失败,而 Facebook 和电子邮件登录成功
- ios - 为什么我不能在 Xcode 12 中覆盖 isEqual(_ object:)?