2015-06-20 511 views
0

這裏是我的JSON響應的樣子:對象的內部JSON更新陣列

"_id" : 537, 
    "quizzes" : [ 
     { 
      "wk" : 1, 
      "score" : [ 
       10 
      ] 
     }, 
     { 
      "wk" : 2, 
      "score" : [ 
       8 
      ] 
     }, 
     { 
      "wk" : 3, 
      "score" : [ 
       5 
      ] 
     }, 
     { 
      "wk" : 4, 
      "score" : [ 
       6 
      ] 
     } 
    ] 
} 

我試圖更新裏面的對象之一比分陣列,這是我的嘗試吧:

db.collection('connect').update({_id: id}, {$push: { quizzes[0]: { score: 89 } }}); 
+0

什麼是預期的結果?如果您希望更新分數數組,以便它仍然是單個元素數組,請考慮使用更新運算符修飾符'「$ set」:{0} {0} {0} {0}解決方案 – chridam

回答

1

我認爲你正在尋找

db.collection('connect').update({_id: id}, {$set: { "quizzes.0.score":89} }) 

一個更好的辦法來做到這一點是不是對測驗陣列和使用的指數回覆了「周」屬性

db.collection('connect').update({_id: id,quizzes:{$elemMatch:{"wk":1}}}, {$set: { quizzes.$.score: 89 } }}) 
+0

括號給我一個語法錯誤:SyntaxError:意外的標記[ –

+0

已更新。對不起,錯誤 –

+0

是的,在2分鐘內將標記爲答案。 –

2

嘗試以下更新:

db.collection("connect").update(
    { 
     "_id": id    
    }, 
    { 
     "$set": { 
      "quizzes.0.score.0": 89  
     } 
    } 
); 

它使用dot notation訪問一個數組中的元素,並訪問嵌入文檔的領域。

To access an element of an array by the zero-based index position, concatenate the array name with the dot (.) and zero-based index position, and enclose in quotes:

'<array>.<index>'