【问题标题】:My first mongo insertion (python)我的第一个 mongo 插入(python)
【发布时间】:2015-04-04 02:08:10
【问题描述】:

尝试插入我的第一条数据,如下所示:

{
    "city": "Oakland", 
    "latitude": "37.800427", 
    "longitude": "-122.275880", 
    "state": "California", 
    "zipcode": "94607"
}

当我打电话时:

def establish_client(self):
    self.client = MongoClient('localhost', 27017)
    self.db = self.client['props']

def insert_mongo(self,property_arg):
    props = self.db.props
    props.insert(property_arg) #err line

我收到以下错误消息:

Traceback (most recent call last):
  File "C:\Program Files (x86)\JetBrains\PyCharm Community Edition 3.4.1\helpers\pydev\pydevd_comm.py", line 930, in doIt
    result = pydevd_vars.evaluateExpression(self.thread_id, self.frame_id, self.expression, self.doExec)
  File "C:\Program Files (x86)\JetBrains\PyCharm Community Edition 3.4.1\helpers\pydev\pydevd_vars.py", line 239, in evaluateExpression
    Exec(expression, updated_globals, frame.f_locals)
  File "C:\Program Files (x86)\JetBrains\PyCharm Community Edition 3.4.1\helpers\pydev\pydevd_exec.py", line 3, in Exec
    exec exp in global_vars, local_vars
  File "<string>", line 1, in <module>
  File "C:\Anaconda\lib\site-packages\pymongo\collection.py", line 409, in insert
    gen(), check_keys, self.uuid_subtype, client)
  File "C:\Anaconda\lib\site-packages\pymongo\collection.py", line 386, in gen
    doc['_id'] = ObjectId()
TypeError: 'str' object does not support item assignment

什么给了?

我正在插入的对象是由嵌入在类本身中的以下函数生成的:

def to_JSON(self):
    return json.dumps(self, default=lambda o: o.__dict__,
        sort_keys=True, indent=4)

【问题讨论】:

    标签: python json mongodb pymongo


    【解决方案1】:

    您不需要将字典转储为 JSON 字符串,只需将字典本身传递给 insert()

    来自tutorial 的引用应该可以解决问题:

    MongoDB 中的数据使用 JSON 样式表示(和存储) 文件。 在 PyMongo 中,我们使用字典来表示文档。

    【讨论】:

    • 我转换成字典的原因是数据被插入到一个对象中。我应该直接插入对象吗?
    • @jasonm 您没有提供完整的类定义,但看起来您需要直接使用self.__dict__ 或过滤您需要保留的相关部分。
    • 感谢您让我知道self.__dict__ 这非常有用。绝对是我需要的!
    猜你喜欢
    • 2022-01-07
    • 2014-10-24
    • 1970-01-01
    • 2021-09-07
    • 1970-01-01
    • 2014-08-02
    • 2018-07-02
    • 2014-03-23
    相关资源
    最近更新 更多