将变量传递给mongo更新? [英] Pass variables into mongo updates?

查看:46
本文介绍了将变量传递给mongo更新?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我有一个如下所示的mongo文档:

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已创建或更改.这并不意味着a = {b:3},所以我不想覆盖已经存储在文档中的现有a.z = 1.

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.

我将如何为这些更改编写原子更新?我无法弄清的主要问题是如何将变量传递到命令中以目标子对象为目标. (使用node-mongodb-native)

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)

感谢您的帮助!

更新后的文档如下:

{ 
   "_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] } });
  }
}

您还可以检查以下URL: http://www.mongodb.org /display/DOCS/Updating#Updating-ModifierOperations

You can also check this URL: http://www.mongodb.org/display/DOCS/Updating#Updating-ModifierOperations

这篇关于将变量传递给mongo更新?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆