Pymongo:将数据插入变量集合

时间:2014-08-04 19:51:01

标签: python mongodb oop pymongo self

想象一下,这是我的类,我想将myObject插入到集合中。后者的名称是可变的,取决于配置对象。

我试过了:

class MyClass(Object):

    def __init__(self, config):

        self.config = config
        self.db = config.db
        self.collection = config.db


    def on_data(self, myObject):
        self.db.self.collection.insert(myObject)

和此:

class MyClass(tObject):

    def __init__(self, config):

        self.config = config

        self.db = config.db       
        self.collection = config.db


    def on_data(self, myObject):
        self.db[self.collection].insert(myObject)

没有人工作过!

我也尝试了这个:

class MyClass(tweepy.Object):

    def __init__(self, config):

        self.config = config
        self.connection = config.connection
        self.db = config.db
        self.collection = config.db


    def on_data(self, myObject):
        self.connection[self.db][self.collection].insert(myObject)

我遇到了这个错误:

TypeError: name must be an instance of basestrin

知道config是DBConfig的一个实例:

class DBConfig():
    def __init__(self, db, collection):
        self.connection = Connection()
        self.db = self.connection[db]
        self.collection = self.db[collection]

我该如何解决这个问题?

1 个答案:

答案 0 :(得分:0)

看起来你的样本课中有一些拼写错误。即,您将self.dbself.collection定义为config.db

class MyClass(tweepy.Object):

    def __init__(self, config):
        self.config = config
        self.db = config.db
        # define `self.collection` appropriately
        self.collection = config.collection

    def on_data(self, tweet):
        # just use the collections insert method
        self.collection.insert(myObject)