繁体   English   中英

如何在mongoDb的子文档中添加新的数组元素

[英]How add new array element in sub document in mongoDb

这是我的JSON

{
    "_id" : 2313,
    "project_id" : "313",
    "project_task" : [ 
        {
            "switchName" : "new 2",
            "slot" : "werwr",
            "cdpDeviceId" : "weqqw",
            "migrationEndDate" : "2015-11-24",
            "migrationStartDate" : "2015-11-16",
            "assigned_to" : "1319",
            "task_id" : 1
        }, 
        {
            "switchName" : "new 2",
            "slot" : "werwr",
            "cdpDeviceId" : "weqqw",
            "migrationEndDate" : "2015-11-15",
            "migrationStartDate" : "2015-11-24",
            "assigned_to" : "",
            "task_id" : 2
        }, 
        {
            "switchName" : "new 2",
            "slot" : "werwr",
            "cdpDeviceId" : "weqqw",
            "migrationEndDate" : "",
            "migrationStartDate" : "",
            "assigned_to" : "",
            "task_id" : 3
        }
      ]
}

在这个数组中,我需要为子文档添加新元素,我的期望是这样

  {
        "switchName" : "new 2",
        "slot" : "werwr",
        "cdpDeviceId" : "weqqw",
        "migrationEndDate" : "2015-11-24",
        "migrationStartDate" : "2015-11-16",
        "assigned_to" : "1319",
        "task_id" : 1,
        "newKey" : "123"
    }

db.getCollection('tableName').update({"_id" : ObjectId("2313")}, {$push: { "project_task.1.newKey": "123"}})

但我有这样的感觉

{
        "switchName" : "new 2",
        "slot" : "werwr",
        "cdpDeviceId" : "weqqw",
        "migrationEndDate" : "2015-11-15",
        "migrationStartDate" : "2015-11-24",
        "assigned_to" : "",
        "task_id" : 2,
        "newKey" : [ 
            "123"
        ]
    }  

还有任何功能可以为子文档中的所有数组添加相同的元素,而不是使用PHP进行循环。

请帮帮我!!

是的,我找到了简单的解决方案

使用$ set代替$ pull

查询将是这样,

db.getCollection('tableName').update({"_id" : ObjectId("2313")}, {$set: { "project_task.1.newKey": "123"}})

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM