Python / 字典 / 列表 / Mongo插入问题 - 新手
抱歉,我正在努力理解和适应字典和列表这两种对象。
我正在通过他们的ebaysdk调用eBay的API,想把从中获取的商品存储到Mongo数据库中,作为文档。很简单。
这是将要返回的一个示例结构:
<timestamp>2009-09-04T00:47:12.456Z</timestamp>
<searchResult count="2">
<item>
<itemId>230371938681</itemId>
<title>Harry Potter and the Order of the Phoenix HD-DVD</title>
<globalId>EBAY-US</globalId>
<primaryCategory>
<categoryId>617</categoryId>
<categoryName>DVD, HD DVD & Blu-ray</categoryName>
</primaryCategory>
我尝试了500次这个代码,简化到最基本的样子,这就是我现在的代码。
from ebaysdk import finding
from pymongo import MongoClient
api = finding(appid="billy-40d0a7e49d87")
api.execute('findItemsByKeywords', {'keywords': 'potter'})
listings = api.response_dict()
client = MongoClient('mongodb://user:pass@billy.mongohq.com:10099/ebaystuff')
db = client['ebaycollection']
ebay_collection = db.ebaysearch
for key in listings:
print key
ebay_collection.insert(key)
会出现这个错误:
Traceback (most recent call last):
File "ebay_search.py", line 34, in <module>
ebay_collection.insert(key)
File "/Library/Python/2.7/site-packages/pymongo/collection.py", line 408, in insert
self.uuid_subtype, client)
File "/Library/Python/2.7/site-packages/pymongo/collection.py", line 378, in gen
doc['_id'] = ObjectId()
TypeError: 'str' object does not support item assignment
其实很简单。我只想把每个商品添加为一个文档。
1 个回答
3
像字符串这样的不可变类型不能用作文档,因为它不允许添加额外的字段,比如MongoDB要求的_id
字段。你可以把字符串放在一个字典里,这样就可以作为一个包装文档使用:
key_doc = {'key': key}
ebay_collection.insert(key_doc)