1024programmer Java python–PyMongo cursor iteration

python–PyMongo cursor iteration

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()
def set_data(self, data):
self.age = data['age']
self.gender = data['gender']

This way I can simply call :

age = obj.age
gender = obj.gender

Or some other helper function to extract data from each document


I don’t see how what you’ve shown could be done more conveniently:


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/

This article is from the internet and does not represent1024programmerPosition, please indicate the source when reprinting:https://www.1024programmer.com/736967

author: admin

Previous article
Next article

Leave a Reply

Your email address will not be published. Required fields are marked *

Contact Us

Contact us


Online consultation: QQ交谈

E-mail: [email protected]

Working hours: Monday to Friday, 9:00-17:30, holidays off

Follow wechat
Scan wechat and follow us

Scan wechat and follow us

Follow Weibo
Back to top