【问题标题】:Pymongo : Insert data to a variable collectionPymongo:将数据插入变量集合
【发布时间】:2014-08-04 19:51:01
【问题描述】:

想象这是我的班级,我想将 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]

我该如何解决这个问题?

【问题讨论】:

    标签: python mongodb oop pymongo self


    【解决方案1】:

    看起来您的示例类中有一些拼写错误。即,您将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)
    

    【讨论】:

      猜你喜欢
      • 2020-09-15
      • 2019-02-25
      • 2014-11-12
      • 2022-01-04
      • 1970-01-01
      • 1970-01-01
      • 2017-03-17
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多