1
I want to update the value of the 'shouldSendAlert' key in a mongoDB document that is in the following structure:
{
"_id" : ObjectId("5c61c4db46d18e1092c5b024"),
"service" : "SRVPVD",
"menu" : [
{
"sub" : [
{
"options" : [
{
"item" : [
{
"name" : "",
"actions" : [
{
"name" : "communicateClient",
"value" : true
},
{
"name" : "shouldSendAlert",
"value" : false
}
]
}
],
"name" : "Technology Support"
},
{
"item" : [
{
"name" : "",
"actions" : [
{
"name" : "communicateClient",
"value" : true
}
]
}
],
"name" : "Company Support"
}
],
"name" : "Support"
},
{
"name" : " FAQ"
}
],
"name" : "Help"
}
]
}
I managed to achieve this goal, with a multiple $elemMatch query and using a foreach for each array within JSON to get to 'shouldSendAlert':
{
let menuItems = db.getCollection('menumodels').find({menu: {$elemMatch: {name: 'Help',sub: {$elemMatch: {name: 'Support',motivos: {$elemMatch: {name: 'Technology Support'}}}}}}});
menuItems.forEach((r) => {
r.menu.forEach(menuItem => {
if (menuItem.name == 'Help') {
menuItem.sub.forEach(sub => {
if (sub.name == 'Support') {
sub.motivos.forEach(motivo => {
if (motivo.name == "Technology Support") {
motivo.item[0].actions.forEach(action => {
if (action.name == 'shouldSendAlert') {
action.value = true;
db.getCollection('menumodels').update({_id: r._id}, {$set: {menu: r.menu}})
}
})
}
})
}
})
}
})
});
}
Is it necessary, in terms of performance, to do this operation in a more intelligent way? Use all of these $elemMatch and foreach within foreach, significantly impact performance?
Thanks for the tips.
I don’t get it, but is it something like that? structure.menu.find(x => x.name === 'Help').sub.find(x => x.name === 'Support').options.find(x => x.name === 'Technology Support'). item[0].actions.find(x => x.name === 'shouldSendAlert'). value = true;
– RDyego
@Rdyego, as I mentioned in the question, the code works. If you notice the line
db.getCollection('menumodels').find({menu: {$elemMatch: {name: 'Help',sub: {$elemMatch: {name: 'Support',motivos: {$elemMatch: {name: 'Technology Support'}}}}}}});
The query returns me an array with the expected document. I want to know if it needs to be refactored for performance reasons. For example: using multiple $elemMatch nested, is very expensive?– MatheusPedro
There are 5 nested foreach s, this is very complex. Even for maintenance is not simple.
– RDyego