更新具有数组和对象键的嵌套对象是动态来的

时间:2015-02-02 11:43:50

标签: node.js mongodb mongodb-query

我有一种情况需要执行查询,其中有一个动态密钥生成来添加数组中的数据,如

var tp = 'unique_key';
db.sr_caller_info.update({caller:9967771131, month:201501},{$push :{ data:{tp:{
    "abc" : 12,
    "xyz" : 30,
    "start_epoch" : "",
    "answer_epoch" : "",
    "end_epoch" : "",
    "file" : "xxx",
}}}})

我的数据库结构如下

{
  "caller": xxxxx,
  "circle": "xxxx",
  "data": {
    "unique_key1": [
      {
        "abc": 12,
        "xyz": 30,
        "start_epoch": "",
        "answer_epoch": "",
        "end_epoch": "",
        "file": "xxx",

      },
      {
        "abc": 12,
        "xyz": 30,
        "start_epoch": "",
        "answer_epoch": "",
        "end_epoch": "",
        "file": "xxx",

      }
    ],
    "unique_key": [
      {
        "abc": 12,
        "xyz": 30,
        "start_epoch": "",
        "answer_epoch": "",
        "end_epoch": "",
        "file": "xxx",

      },
      {
        "abc": 12,
        "xyz": 30,
        "start_epoch": "",
        "answer_epoch": "",
        "end_epoch": "",
        "file": "xxx",

      },
      {
        "abc": 12,
        "xyz": 30,
        "start_epoch": "",
        "answer_epoch": "",
        "end_epoch": "",
        "file": "xxx",

      }
    ]
  },
  "month": 201501
}

我正在使用nodejs mongo驱动程序1.4 所以我想基本上通过创建动态嵌套密钥来进行更新。

由于

1 个答案:

答案 0 :(得分:1)

怎么样:

var actual_obj = 'obj2';
var mongoPushObj = {};
pushObj[actual_obj + '.array'] = { "namefield": "text3" };

db.collection('mongoCollection').update({ 'id':1234 }, { $push: pushObj });