2014-11-21 59 views
1

創建嵌套數組的對象這是我收集的MongoDB - 更新或Pymongo

{ 
    "_id" : '50001', 
    "data" : 
     [ 
      { 
        "name" : "ram", 
        "grade" : 'A' 
      }, 
      { 
        "name" : "jango", 
        "grade" : 'B' 
      }, 
      { 
        "name" : "remo", 
        "grade" : 'A' 
      } 
     ] 
} 

這裏我要更新對象對應於「名」:「詹」,並必須建立一個新項數組如果「jango」不存在。

我可以創建一個新條目但在「創建或更新」中失敗。

我試過這種方式蒙戈解釋

db.MyCollection.update({'_id': '50001', "data.name" :"jango"}, {'$set':{'data': {'data.$.grade':'A'}}}, upsert=true) 

但顯示

not okForStorage 

回答

0

你幾乎有:

db.YourCollection.update(
    { '_id':'50001', <-- to find document 
    'data.name': 'jango' < -- to find element of the array 
    }, 
    { '$set': { "data.$.grade" : 'A' } } <-- with .$ you reference array element from first argument 
) 

Link to documentation

+1

但我只需要創建一個像{「名」的新條目:「詹」,「品位」 :'A'},如果我搜索的名字不在那裏。 – ManikandanV 2014-11-21 14:21:52

0

蒙戈嵌套的UPDATE啊,你應該知道的位置或$更新值的下方可以幫助

db.collecionName.update(
    {'_id': '50001', "data.name" :"jango"}, 
    {'$set':{'data.1.grade':'A'}}, upsert=true) 

db.collecionName.update(
    {'_id': '50001', "data.name" :"jango"}, 
    {'$set':{'data.$.grade':'A'}}, upsert=true) 
+0

但我需要搜索而不考慮數組索引。只有我能夠知道這個名字。 – ManikandanV 2014-11-21 14:25:01

+0

如果搜索名稱不存在,這將不會創建新的條目。 – ManikandanV 2014-11-21 14:29:43

+0

爲此,你應該嘗試mongo地圖減少它會幫助你。 – Yogesh 2014-11-21 14:44:46