2

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}}
   } 
} 
fancy
  • 48,619
  • 62
  • 153
  • 231
  • Is your mongo document schema "fixed" - i.e. do you have the ability to change the schema of the document slightly to make your task easier, or is it not under your control? – Asya Kamsky May 17 '12 at 16:42
  • Also, could you add what the full object would look like after this update is applied? It's not clear to me what you want, if it's not to overwrite a:{z:1} as you cannot have a:{z:1},a:{b:3} - you cannot have the same key twice. So do you want a:[{z:1},{b:3}] which is not your current schema or do you want something else? – Asya Kamsky May 17 '12 at 17:05
  • I control the schema, and I edited to show the full doc. Thanks very much Asya! (I can also change the schema of the update objects sent from the client if there is a better way to do this) – fancy May 17 '12 at 17:32

2 Answers2

1
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

0

variables, here dt is date and review, rating & price can be another variable Python: 3.x

rev = str(dt)+'_review'
rat = str(dt)+'-rating'
pri = str(dt)+'_price'
col.update_one({'brand':brand,'product':product},{'$set': {rev : review, rat : rating, pri : price}})

Output:

2019-04-23_review: 1234
2019-04-23_rating: 2345
2019-04-23_price: 1234
Mono
  • 53
  • 1
  • 6