2015-04-04 44 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