2017-04-10 34 views
1

我使用Pymongo操縱集合女巫,看起來像下面這樣的結構:如何使用Pymongo在文檔中插入對象?

{ 
    Client1:{ 
     "_id" : "Client1" 
     Project1:{ 
      Software1:{ 
       language : "Python", 
       complexity : "Low" 
      } 
      Software2:{ 
       language : "C#", 
       complexity : "Low" 
      } 
      Software3:{ 
       language : "Java", 
       complexity : "Hard" 
      } 
     } 
    } 
} 

在這種情況下,我tryed的許多方法來更新插入一個新的Software文檔Client1,但我可以沒有找到一種方法或功能來做到這一點。

所以我的問題是:在這個範圍內,我怎樣才能插入一個新的Software而不排除現有的項目?

這裏是我試圖,但沒有工作:

client = "Client1" 
client = collection.find_one({"_id": client}) 

project = "Project1" 

software = str(raw_input("Enter with the software to be added to project: ")) 

language = str(raw_input("Enter with the software language: ")) 

complexity = str(raw_input("Enter with the software complexity: ")) 

collection.update({"_id" : client["_id"], }, {"$set" : { 
                  client[project] : {software : {"language": language, "complexity" : complexity}} 
                 } 
               }) 

,我得到的錯誤是:在包含client[project] : {software : {"language": language, "complexity" : complexity}}

因爲現在,感謝您的關注行unhashable type: 'dict'

回答

0

你正在嘗試使用不可變的變量在字典中創建一個鍵。在這種情況下,client[project]是一個字典,你正在使用它作爲另一個字典中的關鍵字。我想你只是想讓你的鑰匙成爲project

project : {software : {"language": language, "complexity" : complexity}} 
+0

It Works!非常感謝,現在我的下一個問題是更新'Software'屬性,我會盡力找到一種方法。 –

+0

太棒了,很高興聽到! – Alex

相關問題