Reputation: 45
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!!
Upvotes: 0
Views: 61
Reputation: 45
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"}})
Upvotes: 1