簡體   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