I want to create and handle cursors in python just like the cursors themselves work in mongo. I know the expected way is to do ‘result = collection.find()’ and do ‘for result in result’ but I Want to wrap the iteration functionality in a class. I want to be able to create a new class object and call a function such as init_cursor() to establish a database connection and perform a lookup that returns a cursor. Then I want to have a get_next() function that will Move to the next result and set the class data members based on the result. Here is the pesudo code:
class dataIter():
def __init__(self):
self.collection = pymongo.Connection().db.collection
self.cursor = self.collection.find({}) #return all
self.age = None
self.gender = None
def get_next(self):
if self.cursor.hasNext():
data = self.cursor.next()
self.set_data(data)
def set_data(self, data):
self.age = data['age']
self.gender = data['gender']
This way I can simply call :
obj.get_next()
age = obj.age
gender = obj.gender
Or some other helper function to extract data from each document
Workaround:
I don’t see how what you’ve shown could be done more conveniently:
p>
col = pymongo.Connection().db.collection
cur = col.find({})
obj = next(cur, None)
if obj:
age = obj['age']
gender = obj['gender']
It is not clear how this wrapper Useful. Also, if your real focus is on the ORM, don’t reinvent the wheel when it exists: http://mongoengine.org/