2015-04-04 45 views
1

试图插入我的第一块,看起来像这样的数据:我的第一个蒙戈插入(蟒蛇)

{ 
    "city": "Oakland", 
    "latitude": "37.800427", 
    "longitude": "-122.275880", 
    "state": "California", 
    "zipcode": "94607" 
} 

当我打电话:

def establish_client(self): 
    self.client = MongoClient('localhost', 27017) 
    self.db = self.client['props'] 

def insert_mongo(self,property_arg): 
    props = self.db.props 
    props.insert(property_arg) #err line 

我收到以下错误信息:

Traceback (most recent call last): 
    File "C:\Program Files (x86)\JetBrains\PyCharm Community Edition 3.4.1\helpers\pydev\pydevd_comm.py", line 930, in doIt 
    result = pydevd_vars.evaluateExpression(self.thread_id, self.frame_id, self.expression, self.doExec) 
    File "C:\Program Files (x86)\JetBrains\PyCharm Community Edition 3.4.1\helpers\pydev\pydevd_vars.py", line 239, in evaluateExpression 
    Exec(expression, updated_globals, frame.f_locals) 
    File "C:\Program Files (x86)\JetBrains\PyCharm Community Edition 3.4.1\helpers\pydev\pydevd_exec.py", line 3, in Exec 
    exec exp in global_vars, local_vars 
    File "<string>", line 1, in <module> 
    File "C:\Anaconda\lib\site-packages\pymongo\collection.py", line 409, in insert 
    gen(), check_keys, self.uuid_subtype, client) 
    File "C:\Anaconda\lib\site-packages\pymongo\collection.py", line 386, in gen 
    doc['_id'] = ObjectId() 
TypeError: 'str' object does not support item assignment 

是怎么回事?被嵌入在类本身下面的函数产生

我认为我正在插入对象:

def to_JSON(self): 
    return json.dumps(self, default=lambda o: o.__dict__, 
     sort_keys=True, indent=4) 

回答

3

你并不需要倾倒字典成JSON字符串,只是把字典本身insert()。使用JSON风格 文件

数据MongoDB中表示(并存储):从tutorial

报价应该明确的事情了。 在PyMongo中,我们使用字典来表示文档。

+0

我转换为字典中的原因是,被插入的对象的数据。我应该直接插入对象吗? – 2015-04-04 02:52:46

+0

@jasonm你没有提供完整的类定义,但它看起来像你需要直接使用'self .__ dict__'或过滤它需要保留的相关部分。 – alecxe 2015-04-04 04:22:43

+0

感谢让我意识到“self .__ dict__”这非常有用。绝对是我需要的! – 2015-04-04 18:28:28