[英]TypeError: 'str' object does not support item assignment with 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
>>>
我究竟做錯了什么?
“插入”調用需要一個有效的對象,而不是字符串。 您的意思是這樣的嗎:
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)
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.