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)))
發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章