Manish Gupta
Manish Gupta

Reputation: 4656

MongoDB query result cursor is unexpectedly empty when used multiple times

My code:

from pymongo import MongoClient

    class NewOrders:

        def __init__(self):
            self.client = MongoClient('localhost',27017)
            self.db = self.client['Flipkart']
            self.sale_order = self.db['sale_order'].find({'status':'APPROVED'})

        def getOrderItemId(self):
            oiids = []
            for each in self.sale_order:
                oiids.append(each['orderItemId'])
            return oiids

        def getStatus(self):
            stts = []
            for each in self.sale_order:
                stts.append(each['status'])
            return stts

I am trying to call the above two methods from a single class object like:

x = NewOrders()
print x.getOrderItemId()
print x.getStatus1()

I get a response like:

['OD1','OD2','OD3']
[]

When i use two different class object i get:

['OD1','OD2','OD3']
['APPROVED','APPROVED','APPROVED']

Why I am not able to call both via a single object?

Upvotes: 0

Views: 1609

Answers (1)

Pinetwig
Pinetwig

Reputation: 695

The find method of a collection returns a cursor, which can iterate over the results a single time. You can use the rewind method to return the cursor to the start again, or you can cache the results of the query in a list, like vaultah suggested.

Upvotes: 3

Related Questions