这是我的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 for循环。
请帮帮我!!
答案 0 :(得分:1)
是的,我找到了这个简单的解决方案
使用$ set而不是$ pull
查询将是这样的,
db.getCollection('tableName').update({"_id" : ObjectId("2313")}, {$set: { "project_task.1.newKey": "123"}})