epskip epskip - 4 months ago 29
Node.js Question

Updating a mongoDb collection on Nested Arrays

I have a json like this. I want to add an agent to technical

departmentName
just like how it is there in support. I have been trying with
$push
and add to set but it didn't help.

This is what I have tried:

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) { }
);


and this

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


I would like to how to write a query for this

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


The end result should look like this:

{
"_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"
}
]
}

Answer

You should be able to use the $ positional operator in your update as follows:

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

This enables you to identify an element in an array to update without explicitly specifying the position of the element in the array.

Comments