TypeError:'str'对象不支持使用 PyMongo (MongoDB API) 进行项目分配



我正在尝试遵循MongoDB - 快速指南,但出现以下错误:

alexus@mbp:~ $ python
Python 2.7.10 (default, Oct 23 2015, 18:05:06) 
[GCC 4.2.1 Compatible Apple LLVM 7.0.0 (clang-700.0.59.5)] on darwin
Type "help", "copyright", "credits" or "license" for more information.
>>> import json
>>> from pymongo import MongoClient
>>> client = MongoClient('mongodb://192.168.99.100:32768/')
>>> db = client['test']
>>> collection = db['c']
>>> 
>>> obj = 'adc83b19e793491b1c6ea0fd8b46cd9f32e592fc:{tag1:value1}'
>>> print obj
adc83b19e793491b1c6ea0fd8b46cd9f32e592fc:{tag1:value1}
>>> json.dumps(obj, separators=(',', ':'), sort_keys=True)
'"adc83b19e793491b1c6ea0fd8b46cd9f32e592fc:{tag1:value1}"'
>>> db.c.insert(json.dumps(obj, separators=(',', ':'), sort_keys=True))
Traceback (most recent call last):
  File "<stdin>", line 1, in <module>
  File "/Library/Python/2.7/site-packages/pymongo/collection.py", line 2199, in insert
    check_keys, manipulate, write_concern)
  File "/Library/Python/2.7/site-packages/pymongo/collection.py", line 578, in _insert
    gen(), check_keys, self.codec_options, bwc)
  File "/Library/Python/2.7/site-packages/pymongo/collection.py", line 546, in gen
    doc['_id'] = ObjectId()
TypeError: 'str' object does not support item assignment
>>> 

我做错了什么?

"insert" 调用需要一个有效的对象,而不是一个字符串。你的意思是这样的:

db.c.insert({'adc83b19e793491b1c6ea0fd8b46cd9f32e592fc':{'tag1':'value1'}})

我和 PyMongo 一样遇到了同样的问题,我找到了以下解决方案:

import json    
valuestr = json.dumps(obj, separators=(',', ':'), sort_keys=True)
value = json.loads(valuestr) # <-- returned data is not string
db.c.insert(value)

最新更新