2017-01-15 4 views
0

Ich habe die folgende Struktur (vereinfacht) von Daten:MongoDB: Ändern Sie den Wert eines Schlüssels in einem verschachtelten Array

{ 
quiz_id : ObjectId(), 
questions : [{ 
     question : "xyz", 
     options : [{ 
      option_text : "a" 
      }, 
      { 
      option_text : "b" 
      }] 
     }, { 
     question : "pqr", 
     options : [{ 
      option_text : "s" 
      }, 
      { 
      option_text : "t" 
      }] 
     }] 
}   

Jetzt möchte ich Update dies durch hinzufügen answer_count : 0 jeder Option hinzufügen. So neue Datenstruktur ist:

{ 
quiz_id : ObjectId(), 
questions : [{ 
     question : "xyz", 
     options : [{ 
      option_text : "a", 
      answer_count : 0 
      }, 
      { 
      option_text : "b", 
      answer_count : 0 
      }] 
     }, { 
     question : "pqr", 
     options : [{ 
      option_text : "s", 
      answer_count : 0 
      }, 
      { 
      option_text : "t", 
      answer_count : 0 
      }] 
     }] 
} 

Wie dies in mongodb tun?

Antwort

0

Sie können alle Dokumente durchlaufen, um die answer_count und die Verwendung db.save() hinzuzufügen, um das Dokument zu aktualisieren.

db.foo.find().forEach(function(doc){ 
    for(var question of doc.questions) { 
     for (var option of question.options) { 
      option.answer_count = 0; 
     } 
    } 
    db.foo.save(doc); 
}) 
Verwandte Themen