python - 在mongodb中插入python对象

标签 python json mongodb

各位, 我只是花了很多时间试图查找这个——我应该遗漏一些基本的东西。

我有一个python对象,我想做的就是把这个对象插入mondodb。

这就是我所拥有的:

from pymongo import Connection
import json

conn = Connection()
db = conn.cl_database
postings = db.postings_collection

class Posting(object):
    def __init__(self, link, found=None, expired=None):
        self.link = link
        self.found = found
        self.expired = expired

posting = Posting('objectlink1')
value = json.dumps(posting, default=lambda x:x.__dict__)
postings.insert(value)

抛出此错误:

Traceback (most recent call last):
  File "./mongotry.py", line 21, in <module>
postings.insert(value)
  File "build/bdist.macosx-10.7-intel/egg/pymongo/collection.py", line 302, in insert
  File "build/bdist.macosx-10.7-intel/egg/pymongo/database.py", line 252, in _fix_incoming
  File "build/bdist.macosx-10.7-intel/egg/pymongo/son_manipulator.py", line 73, in transform_incoming
TypeError: 'str' object does not support item assignment

好像是因为 json.dumps() 返回一个字符串。

现在,如果我在插入之前做了大量的值,它工作正常:

posting = Posting('objectlink1')
value = json.dumps(posting, default=lambda x:x.__dict__)
value = json.loads(value)
postings.insert(value)

最直接的做法是什么?

谢谢!

最佳答案

您的初始代码中的 value 是什么?

应该是dict而不是类实例

这应该可行:

postings.insert(posting.__dict__)

关于python - 在mongodb中插入python对象,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/10292368/

相关文章:

Python散点图在背景图像上进行数据验证

json - ASP.Net MVC3 - 为什么对 JSON 模型绑定(bind)的默认支持无法解码为枚举类型?

json - Node.js Express3 到 Express4 迁移 - 解析器使用

javascript - Mongodb 版本 3+ : how to insert new document only if it doesn't exist and get the result

python - 修改Python脚本批量转换目录下所有 "WOFF"文件

python & BeautifulSoup : How to extract a tags' value which is in many others tags?

python - 如何使用 Poetry 从现有项目中导入 requirements.txt

json - Firebase 数据到 Google BigQuery

javascript - 如何从 MongoDB 数组中删除重复的对象?

node.js - 仅在 mongodb 聚合中返回具有最新子文档的文档