1

Is it possible to retrieve a list of documents while iterating through a mongodb cursor? What I mean by that is:

for item in collection.find():
    # do stuff with the document

Item is just one document, but could I somehow retrieve a list and continue iterating through the cursor? (because collection.find()[:2] returns a list but you don't get to keep your cursor). I know I could use some counter to do that, but is there a syntactic sugar for it?

It looks like cursors can be zipped like lists:

for item1, item2 in zip(collection.find(), collection.find({'_id': {'$gt': 0}})):
    print((item1, item2))

Edit: In this solution it's shown that you can get the entire collection as a list (if it fits in RAM) and iterate through it. This fits my use case, but what if it doesn't fit in RAM?

Community
  • 1
  • 1
thehousedude
  • 611
  • 6
  • 16

1 Answers1

0

You can use any of the rolling-window generators in the answers to this question, and apply it to the cursor. E.g.

cursor = collection.find()
for doc1, doc2 in window(cursor, n=2):
    print(doc1, doc2)

Or

for doc1, doc2, doc3 in window(cursor, n=3):
    print(doc1, doc2, doc3)

Etc.

Community
  • 1
  • 1
shx2
  • 61,779
  • 13
  • 130
  • 153