简体   繁体   中英

How add new array element in sub document in mongoDb

This is my 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
        }
      ]
}

In this array i need to add new element for sub document my expectation like this

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

But I got this like,

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

Also is there any function to add same element for all of the array in a sub document rather than using PHP for loop.

Please help me out!!

Yeah I found that simple solution

using $set instead of $pull

The query would be like this,

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

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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