简体   繁体   English

如何高效使用PyMongo cursor

[英]How to efficiently use PyMongo cursor

Please propose ways to access data returned from collections.find() in an efficient manner.请提出以有效方式访问从collections.find()返回的数据的方法。

Is a for iteration the recommended way?迭代是for的方法吗? How do I keep the character of a cursor being an Iterable ?如何保持 cursor 的特征为Iterable

Thx谢谢

There are several ways to efficiently access the data returned by a PyMongo cursor:有几种方法可以有效地访问 PyMongo cursor 返回的数据:

  1. Iterating through the cursor: You can iterate through the cursor using a for loop, as you mentioned.遍历 cursor:如您所述,您可以使用 for 循环遍历 cursor。 This is a simple and easy way to access the data, but it can be inefficient if the cursor returns a large amount of data, as the entire dataset will be loaded into memory.这是访问数据的一种简单易行的方法,但如果 cursor 返回大量数据,则效率可能会很低,因为整个数据集将加载到 memory 中。

  2. Using the limit() method: You can use the limit() method to limit the number of documents returned by the cursor, which can be useful if you only need to access a small subset of the data.使用limit()方法:您可以使用limit()方法来限制 cursor 返回的文档数量,如果您只需要访问一小部分数据,这将很有用。

  3. Using the batch_size() method: You can use the batch_size() method to specify the number of documents the cursor should return in each batch.使用batch_size()方法:您可以使用batch_size()方法指定 cursor 应在每批中返回的文档数。 This can be more efficient than iterating through the entire cursor at once, as it reduces the amount of data that needs to be loaded into memory at any given time.这比一次迭代整个 cursor 更有效,因为它减少了在任何给定时间需要加载到 memory 中的数据量。

  4. Using the skip() method: You can use the skip() method to skip a certain number of documents in the cursor before returning the rest of the documents.使用skip()方法:可以使用skip()方法跳过cursor中的一定数量的文档,然后返回rest的文档。 This can be useful if you only want to access a specific subset of the data.如果您只想访问数据的特定子集,这会很有用。

Regardless of the method you choose, the cursor will maintain its iterable character and you can continue to use it as an iterable object.无论您选择哪种方法,cursor 都将保持其可迭代的特性,您可以继续将其用作可迭代的 object。

A simple:一个简单的:

A cursor implements methods of Iterable and Iterator and behaves as such, would have been the answer.一个 cursor 实现了IterableIterator的方法并且表现如此,这就是答案。

(after diving into the code of PyMongo's cursor.py ) (在深入了解 PyMongo 的代码cursor.py

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM