在嵌套数组上更新mongoDb集合

时间:2016-07-21 09:37:17

标签: node.js mongodb

我有一个这样的json。我想向技术departmentName添加一个代理,就像它支持的那样。我一直在尝试$push并添加到设置但它没有帮助。

这就是我的尝试:

var depName = "Support"; // i get this from a form
db.collection('departments').update(
    { "departments.departmentName": depName },
    {
        $addToSet: {
            "departmentName": depName,
            "agents": {
                "agentName": "xxx", 
                "agentNumber": "xxx"
            }
        }
    }, function(err,result) { }
);

和这个

db.collection('departments').update(
    { "departments.departmentName": depName },
    { 
        $addToSet: {
            "agents": {
                "agentName": "xxx", 
                "agentNumber": "xxx"
            }
        }
    }, function(err,result) { }
);

我想如何为此编写查询

{
    "_id": {
        "$oid": "578f6377dcba0f1ad368b7bb"
    },
    "name": "xxx",
    "departments": [
        {
            "departmentName": "Support",
            "agents": [
                {
                    "agentName": "xxx",
                    "agentNumber": "xxx"
                },
                {
                    "agentName": "xxx",
                    "agentNumber": "xxx"
                }
            ]
        },
        {
            "departmentName": "Technical"
        },
        {
            "departmentName": "Customer Care"
        }
    ]
}

最终结果应如下所示:

 {
    "_id": {
        "$oid": "578f6377dcba0f1ad368b7bb"
    },
    "name": "xxx",
    "departments": [
        {
            "departmentName": "Support",
            "agents": [
                {
                    "agentName": "xxx",
                    "agentNumber": "xxx"
                },
                {
                    "agentName": "xxx",
                    "agentNumber": "xxx"
                }
            ]
        },
        {
            "departmentName": "Technical",
            "agents": [
                {
                    "agentName": "xxx",
                    "agentNumber": "xxx"
                },
            ]
        },
        {
            "departmentName": "Customer Care"
        }
    ]
}

1 个答案:

答案 0 :(得分:1)

您应该能够在更新中使用$ positional operator,如下所示:

db.collection('departments').update(
    { "departments.departmentName": depName },
    { 
        "$addToSet": {
            "departments.$.agents": {
                "agentName": "foo", 
                "agentNumber": "123"
            }
        }
    }, function (err, result) {}
)

这使您可以识别要更新的数组中的元素,而无需显式指定元素在数组中的位置。