Welcome to OStack Knowledge Sharing Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
1.2k views
in Technique[技术] by (71.8m points)

mongodb - Query nested elements from unknown number of arrays

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

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Answer

0 votes
by (71.8m points)
Waitting for answers

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome to OStack Knowledge Sharing Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...