1

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
4
  • 1- the answer is $unwind (aggregation) stackoverflow.com/questions/26463032/searching-in-mongodb/… 2- stackoverflow.com/questions/26463032/searching-in-mongodb/… Commented Nov 10, 2014 at 21:00
  • @Disposer: Thank you for your input. Isn't $unwind used to generate a document for each element in the array? You posted the same link twice. Commented Nov 11, 2014 at 6:33
  • 1
    @CruelIO you want two different output like first contains array of all name and seconds contains which match Children.Name="jack" or Children.Children.Name="jack" is right? Commented Nov 11, 2014 at 9:31
  • @yogesh That is correct Commented Nov 11, 2014 at 9:38

1 Answer 1

2

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.

Sign up to request clarification or add additional context in comments.

Comments

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.