Querying to get an element from an array that is nested in an object is not a big deal. But, when you have a self-repeating structure that is nested within itself, it seems to become much more complicated. Here is an example document:
{
"_id": "1",
"name": "Alpha",
"options": [
{
"_id": "2",
"name": "Bravo",
"options": [
]
},
{
"_id": "3",
"name": "Charlie",
"options": [
{
"_id": "4",
"name": "Delta",
"options": [
...etc
]
}
]
}
]
}
As you can see, here we have a number of arrays holding objects that are alike. This is useful for, say, a tabbed interface being configured out of a DB.
What I'm looking to do is actually be able to modify the documents that are further down in the structure without knowing their positions in the ancestor arrays. So far I've only found the "$" update operator helpful when you don't have to deal with more than one level of arrays. But as you can see, there are arrays within objects that are inside of arrays here, so it becomes complicated.
Pushing to an array in the first level is not difficult:
db.myCollection.update({_id: "1", "options._id": "2"}, {$push: {"options.$.options": {...object definition here...}}});
This works. However, when you try to go deeper into the structure, I don't understand how to target the deeper portions of the document.
The following query is not working for me, and I'm hoping somebody could help me out:
db.myCollection.update({_id: "1", "options.options._id": "4"}, {"options.options.$.options": {...object definition here...}});
It whines about how I can't use dot syntax. Which makes sense, because in this case "options.options" is ambiguous. I was hoping that the query selection would have pointed to the right place.
tl;dr: How do you update document portions that are multiple levels deep nested within more than one array where you do not know the index of the target element? You can select it, so you should be able to modify it.
See Question&Answers more detail:
os