web*_*org 4 mongodb nosql pymongo
我正在读关于mongodb的文章.来到这个部分http://www.mongodb.org/display/DOCS/Tutorial它说 -
> var cursor = db.things.find();
> printjson(cursor[4]);
{ "_id" : ObjectId("4c220a42f3924d31102bd858"), "x" : 4, "j" : 3 }
Run Code Online (Sandbox Code Playgroud)
"当以这种方式使用游标时,请注意所有访问过的最高值(上面的光标[4])都会同时加载到RAM中.这对于大型结果集来说是不合适的,因为你的内存不足.应该用作任何返回大量元素的查询的迭代器."
如何使用游标作为迭代器与查询?感谢您的帮助
mar*_*r75 15
你已经标记了你正在使用pymongo,所以我将使用游标作为迭代器给你两个pymongo示例:
import pymongo
cursor = pymongo.Connection().test_db.test_collection.find()
for item in cursor:
print item
#this will print the item as a dictionary
Run Code Online (Sandbox Code Playgroud)
和
import pymongo
cursor = pymongo.Connection().test_db.test_collection.find()
results = [item['some_attribute'] for item in cursor]
#this will create a list comprehension containing the value of some_attribute
#for each item in the collection
Run Code Online (Sandbox Code Playgroud)
此外,您可以通过以下方式设置返回到pymongo驱动程序的批次大小:
import pymongo
cursor = pymongo.Connection().test_db.test_collection.find()
cursor.batchsize(20) #sets the size of batches of items the cursor will return to 20
Run Code Online (Sandbox Code Playgroud)
通常没有必要弄乱批处理大小,但是如果运行驱动程序的计算机在处理查询结果时遇到内存问题和页面错误,则可能必须设置此项以获得更好的性能(这实际上是这样的)对我来说似乎是一个痛苦的优化,我总是保留默认值).
至于javascript驱动程序(启动"shell"时加载的驱动程序),文档的这一部分提醒您不要使用"数组模式".从在线手册:
Shell中的阵列模式
请注意,在某些语言(如JavaScript)中,驱动程序支持"阵列模式".请查看驱动程序文档以了解具体信息.
在db shell中,要在数组模式下使用游标,请使用数组index []操作和length属性.
阵列模式将所有数据加载到RAM中,直到请求的最高索引.因此,它不应该用于任何可以返回大量数据的查询:您将在客户端上耗尽内存.
您也可以在游标上调用toArray().toArray()会将所有对象查询加载到RAM中.