mongoDB update multiple fields in single array element (from form) -
i've seen many variations on question, none specific issue. consider following document:
{ "class" : "english101", "students" : [ { "name" : "julie", "age" : 32, "gpa" : "3.4" }, { "name" : "heather", "age" : 34, "gpa" : "3.8" } ] } i'd update both name , age fields simultaneously. here's i'm trying:
db.test.update( { 'class':'english101', 'students.name':'julie' }, { $set: { 'students.$': { 'name':'jules', 'age':'31' } } } ) the result this:
{ "class" : "english101", "students" : [ { "name" : "jules", "age" : "31", # gpa gone! }, { "name" : "heather", "age" : 34, "gpa" : "3.8" } ] } the problem instead of expected update , $set behavior replaces whole array item, instead of updating supplied fields.
how should doing this?
in case update object, overwrites everything. here correct approach.
db.test.update({ 'class':'english101', 'students.name':'julie' },{ $set: { 'students.$.name': 'jules', 'students.$.age' : 31 } })
Comments
Post a Comment