伙计们,我只是花了很多时间来尝试查找-我应该缺少一些基本知识。
我有一个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在你最初的代码?
value
它不应该是dict类实例
dict
这应该工作:
postings.insert(posting.__dict__)