pymongo最大查询限制

一、背景

在用pyhton遍历mongo数据中时候,发限查询到101行就会阻塞,如下

    lista_a = []
    for info in db.get_collection("dbs").find():
        lista_a.append(info)
        print("info nums=",len(info))

'''结果显示'''
'''info nums=101'''

分析原因:mongodb的find()方法返回游标cursor,可能有一个限制阈值101,参考文档,如下
原文
The MongoDB server returns the query results in batches. The amount of data in the batch will not exceed the maximum BSON document size. To override the default size of the batch, see batchSize() and limit().

New in version 3.4: Operations of type find(), aggregate(), listIndexes, and listCollections return a maximum of 16 megabytes per batch. batchSize() can enforce a smaller limit, but not a larger one.

find() and aggregate() operations have an initial batch size of 101 documents by default. Subsequent getMore operations issued against the resulting cursor have no default batch size, so they are limited only by the 16 megabyte message size.

For queries that include a sort operation without an index, the server must load all the documents in memory to perform the sort before returning any results.
翻译

  • MongoDB服务器批量返回查询结果。批处理中的数据量不会超过最大BSON文档大小。要覆盖批处理的默认大小,请参见batchSize()和limit()。
  • 新版本3.4:类型为find()、aggregate()、listIndexes和listCollections的操作每批最多返回16兆字节。batchSize()可以执行较小的限制,但不能执行较大的限制。
  • find()和aggregate()操作的初始批处理大小默认为101个文档。针对生成的游标发出的后续getMore操作没有默认的批处理大小,因此它们仅受16mb消息大小的限制。 对于包含没有索引的排序操作的查询,服务器必须在返回任何结果之前加载内存中的所有文档来执行排序。

二、解决方案

    lista_a = []
    for info in db.get_collection("dbs").find().batch_size1(5000): #修改最大限制阈
        lista_a.append(info)
        print("info nums=",len(info))

但是这种方法是每次游标返回5000条数据,循环遍历,如果单词查找50000次应该怎么写呢?如下

   lista_a = []
   cousor=db.get_collection("dbs").find().batch_size1(5000)
    for i in range(50000): #修改最大限制阈
        lista_a.append(next(cousor))
        print("info nums=",len(next(cousor)))
發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章