Need help in updating a schema of multi-level nested array of JSON objects

198 views
Skip to first unread message

AlienWare X

unread,
Sep 20, 2018, 6:38:16 PM9/20/18
to mongodb-user

Hi all,

Ill make this very brief and concise. 

My schema is in the first screenshot.

My problem statement is , a user wants to set the in_use property of his IP address of a particular network to 'true'.

How do i achieve that?

Please help.


//The schema
const userSchema = new Schema({
owner: String,
admin: Boolean,
networks: [
//each object is a network
{
network_id: String,
subnet_mask: String,
ip_pool: [
//each object is an IP in the above network
{
ipaddress: String,
gateway: String,
in_use: Boolean,
hostname: String,
pingable: Boolean
}
]
}
]
});

//My approach
users.updateOne({
owner: req.body.username,
networks: {
$elemMatch: {
ip_pool: {
$elemMatch: {
ipaddress: ip
}
}
}
}
}, {
$set: {
'networks.$.ip_pool.$.in_use': true
}
}, (err, result) => {
if (err) throw err;
else if (!result) {
console.log("users not found")
} else {
console.log(result);
//res.json(result);
//res.json({ success : "IP is assigned successfully in users document"})
}
});

Wan Bachtiar

unread,
Sep 28, 2018, 1:31:51 AM9/28/18
to mongodb-user

My problem statement is , a user wants to set the in_use property of his IP address of a particular network to ‘true’.

Hi,

You can combine two array update operators $[] and $[] as mentioned in Update Nested Arrays in Conjunction with $[]

For example, in mongo shell:

db.users.update(
    {"owners": "SOMEVALUE"}, 
    {"$set":{"networks.$[].ip_pool.$[ip].in_use": true}}, 
    {"arrayFilters":[{"ip.ipaddress":"IPVALUE"}], "multi":true})

Regards,
Wan.

Reply all
Reply to author
Forward
0 new messages