0

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!!

1 Answer 1

1

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"}})
Sign up to request clarification or add additional context in comments.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.