PyMongo游标迭代 [英] PyMongo Cursor Iteration

查看:398
本文介绍了PyMongo游标迭代的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我正在寻找在python中创建和处理游标的方法,就像游标在mongo中的本机工作一样.我知道预期的方法是执行结果= collection.find()"并执行用于结果记录",但我正在寻找将迭代功能包装在类中的方法.我希望能够创建一个新的类对象并调用一个函数,例如init_cursor()建立数据库连接并查找返回游标的内容.然后,我希望有一个get_next()函数,该函数将移至下一个结果并根据结果设置类数据成员.这是伪代码:

I'm looking to create and handle a cursor in python the way cursors natively work in mongo. I know the intended way is to do 'result = collection.find()' and do a 'for record in result' but I'm looking to wrap iteration functionality in a class. I'd like to be able to create a new class object and call a function e.g. init_cursor() to make a db connection and do a find returning a cursor. I would then like the have a get_next() function that would move to the next result and set class data members based on the result. Here's 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 would be able to simply call:

obj.get_next()
age = obj.age
gender = obj.gender

或其他一些帮助功能可将数据从每个文档中拉出

or some other help functions to pull data out of each document

推荐答案

我不明白您所显示的内容是否比这样做更方便:

I don't understand how what you are showing is any more convenient that just doing:

col = pymongo.Connection().db.collection
cur = col.find({})

obj = next(cur, None)
if obj:
    age = obj['age']
    gender = obj['gender']

尚不清楚此包装程序有何帮助.另外,如果您真正想要的是ORM,则不要在存在时重新发明轮子: http://mongoengine.org/

Its not clear how this wrapper is helpful. Also, if what you are really after is an ORM, then don't reinvent the wheel when this exists: http://mongoengine.org/

这篇关于PyMongo游标迭代的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆