我最近开始通过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)
我希望做的事情是这样的:
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)
我尝试按照this question使用batch_size(),并将值一直更改到1000000,但似乎没有任何效果(或者我做错了)。
任何帮助都是非常感谢的。请对这个Mongo新手放轻松!
-编辑
谢谢你,凯勒。我想你已经指出了我真正想问的问题,那就是:有没有办法像cx_Oracle模块那样执行collection.findAll()
或cursor.fetchAll()
命令?问题不在于存储数据,而在于尽可能快地从Mongo DB中检索数据。
据我所知,数据返回给我的速度是由我的网络决定的,因为Mongo必须单次获取每条记录,对吗?
发布于 2011-07-13 23:48:04
您是否考虑过这样的方法:
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
或者,类似这样的东西:
# 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
基本上,只要您有足够的RAM来存储结果集,就应该能够在处理之前将它们从游标中拉出并保持不变。这不太可能会快很多,但它将缓解游标的任何减慢,并释放出您可以并行处理数据的自由。
发布于 2011-07-14 03:43:19
您还可以尝试:
results = list(collection.find({'field':value}))
这应该会将所有内容加载到RAM中。
或者这个,如果你的file
不是太大的话:
values = list()
for line in file:
values.append(line[a:b])
results = list(collection.find({'field': {'$in': values}}))
发布于 2013-05-18 02:44:19
toArray()
可能是一个解决方案。基于文档,它首先遍历Mongo上的所有游标,并以数组的形式只返回一次结果。
http://docs.mongodb.org/manual/reference/method/cursor.toArray/
这与list(coll.find())
或[doc for doc in coll.find()]
不同,后者每次获取一个文档到Python,然后返回到Mongo并获取下一个游标。
然而,这个方法并没有在pyMongo上实现...奇怪
https://stackoverflow.com/questions/6680659
复制相似问题