简体   繁体   English

Python / Dictionary / List / Mongo插入问题 - 初学者

[英]Python / Dictionary / List / Mongo insert issues - beginner

Sorry, trying to understand and get used to dictionary and list objects. 对不起,试着理解并习惯了字典和列表对象。

I'm calling eBay's API through their ebaysdk, and want to store the items from it to a collection as documents in Mongo. 我通过他们的ebaysdk调用eBay的API,并希望将其中的项目存储为Mongo中的文档。 Simple. 简单。

Here's a sample of the schema that will be returned: 以下是将返回的架构示例:

<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>

I've tried 500 iterations of this code, stripped down to the most basic here's what I have. 我已经尝试了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)

Will get this error: 会得到这个错误:

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

Simple stuff. 简单的东西。 All I want to do is add each item as a document. 我想要做的就是将每个项目添加为文档。

An immutable type like a string cannot be used as a document because it doesn't allow adding additional fields, like the _id field Mongo requires . 像字符串这样的不可变类型不能用作文档,因为它不允许添加其他字段,例如Mongo要求_id字段 You can instead wrap the string in a dictionary to serve as a wrapper document: 您可以将字符串包装在字典中以用作包装文档:

key_doc = {'key': key}
ebay_collection.insert(key_doc)

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM