CruelIO
CruelIO

Reputation: 18634

MongoDB and Nested Arrays

I have a collection with data like this:

{
    "Name": "Steven",
    "Children": [
        {
            "Name": "Liv",
            "Children": [
                {
                    "Name": "Milo"
                }
            ]
        },
        {
            "Name": "Mia"
        },
        {
            "Name": "Chelsea"
        }
    ]
},
{
    "Name": "Ozzy",
    "Children": [
        {
            "Name": "Jack",
            "Children": [
                {
                    "Name": "Pearl"
                }
            ]
        },
        {
            "Name": "Kelly"
        }
    ]
}

Two questions

  1. Can MongoDB flatten the arrays to a structure like this [Steven, Liv, Milo, Mia,Chelsea, Ozzy, Jack, Pearl,Kelly]
  2. How can I find the a document where name is jack, no matter where in the structure it is placed

Upvotes: 1

Views: 76

Answers (1)

wdberkeley
wdberkeley

Reputation: 11671

In general, MongoDB does not perform recursive or arbitrary-depth operations on nested fields. To accomplish objectives 1 and 2 I would reconsider the structure of the data as an arbitrarily nested document is not a good way to model a tree in MongoDB. The MongoDB docs have a good section of modelin tree structures that present several options with examples. Pick the one that best suits your entire use case - they will all make 1 and 2 very easy.

Upvotes: 2

Related Questions