Val*_*g21 21 python mongodb pymongo
我最近开始通过shell和PyMongo测试MongoDB.我注意到返回游标并尝试迭代它似乎是实际迭代中的瓶颈.有没有办法在迭代期间返回多个文档?
伪代码:
for line in file:
value = line[a:b]
cursor = collection.find({"field": value})
for entry in cursor:
(deal with single entry each time)
Run Code Online (Sandbox Code Playgroud)
我希望做的是这样的:
for line in file
value = line[a:b]
cursor = collection.find({"field": value})
for all_entries in cursor:
(deal with all entries at once rather than iterate each time)
Run Code Online (Sandbox Code Playgroud)
我已经尝试按照这个问题使用batch_size()并将值一直更改为1000000,但它似乎没有任何影响(或者我做错了).
任何帮助是极大的赞赏.这个Mongo新手请轻松一点!
---编辑---
谢谢迦勒.我想你已经指出了我真正想要问的问题,这就是:有什么方法可以进行排序collection.findAll()或cursor.fetchAll()命令,就像cx_Oracle模块一样?问题不在于存储数据,而是尽可能快地从Mongo DB中检索数据.
据我所知,数据返回给我的速度由我的网络决定,因为Mongo必须单次获取每条记录,对吗?
小智 16
您是否考虑过以下方法:
for line in file
value = line[a:b]
cursor = collection.find({"field": value})
entries = cursor[:] # or pull them out with a loop or comprehension -- just get all the docs
# then process entries as a list, either singly or in batch
Run Code Online (Sandbox Code Playgroud)
或者,类似于:
# same loop start
entries[value] = cursor[:]
# after the loop, all the cursors are out of scope and closed
for value in entries:
# process entries[value], either singly or in batch
Run Code Online (Sandbox Code Playgroud)
基本上,只要你有足够的RAM来存储你的结果集,你应该能够将它们从光标中拉出并在处理之前保持它们.这可能不会明显加快,但它可以减轻游标的任何减速,并且如果你已经为此设置,可以让你自由地并行处理数据.
小智 15
你也可以尝试:
results = list(collection.find({'field':value}))
Run Code Online (Sandbox Code Playgroud)
那应该把所有东西都加载到RAM中.
或者这也许,如果你file的不是太大:
values = list()
for line in file:
values.append(line[a:b])
results = list(collection.find({'field': {'$in': values}}))
Run Code Online (Sandbox Code Playgroud)
| 归档时间: |
|
| 查看次数: |
36726 次 |
| 最近记录: |