I have a mongo document that looks like this:
{
"_id" : '4fb2a4809ad7324ccba1f6b8',
"events" : {
"4fb2a4809ad7324ccba1f6b9" : {a:{z:1},b:{z:2},c:{z:3}},
"4fb2a4809ad7324ccba1f610" : {a:{z:1},b:{z:2},c:{z:3}}
}
}
Then my server gets sent a update object.
update = {
_id = '4fb2a4809ad7324ccba1f6b8',
event_id: '4fb2a4809ad7324ccba1f610',
changed_data: {a:{b:3}}
}
a.b = 3 has been created or changed. This doesn't mean a = {b:3} thus I don't want to overwrite the existing a.z = 1 already stored in the document.
How would I about writing an atomic update for these changes? The main thing I can't figure out is how to pass variables into the command to target sub-objects. (using node-mongodb-native)
Thanks for any help!
Updated document would look like:
{
"_id" : '4fb2a4809ad7324ccba1f6b8',
"events" : {
"4fb2a4809ad7324ccba1f6b9" : {a:{z:1},b:{z:2},c:{z:3}},
"4fb2a4809ad7324ccba1f610" : {a:{z:1, b:3},b:{z:2},c:{z:3}}
}
}
for (var id in update.changed_data) {
for (var sub_id in update.changed_data[id]) {
db.collection.update({ "_id" : update._id, "$atomic" : "true" },{ $set: {'events.' + update.event_id + '.'+ id +'.' + sub_id : update.changed_data[id][sub_id] } });
}
}
You can also check this URL: http://www.mongodb.org/display/DOCS/Updating#Updating-ModifierOperations