MK Yung
MK Yung

Reputation: 4581

How to continue reading a Mongodb cursor?

In this simplified example, I have a query that returns 10 documents.

I would like to return the first half (n = 5) to my client first. If he wants to continue reading, he can submit a request and I return him the next half ( n = 5)

in pyMongo:

doc = collection.find({'foo': 'bar'}).limit(10)

A not-so-clever way, IMO, is that I can split the doc cursor into two, give my client doc[:4] then give him doc[5:] upon request.

Is this the best way? Are there any methods that can return the position where I left off, and allow me to come back reading the rest of the documents?

Upvotes: 0

Views: 446

Answers (1)

zero323
zero323

Reputation: 330073

Is there any reason to not to use pymongo.cursor.Cursor.next method?

try:
    c = collection.find({'foo': 'bar'}).limit(10)

    # Take first five
    for in range(5):
        doc = c.next()

    #If you need more
    for in range(5):
        doc = c.next()

 # If there is no next
 except StopIteration:
     pass

Upvotes: 2

Related Questions