A
A
Alexander Sharomet2017-03-29 16:50:35
PHP
Alexander Sharomet, 2017-03-29 16:50:35

How to get childs data in mongodb?

Hello.
Can you tell me how to get the data of attached documents?
Example:

{
    "_id" : ObjectId("11b97aa654bce61356002559"),
    "name" : "Category",
    "childs" : [
        {
            "_id" : ObjectId("22b55aa654bce61356002559"),
            "name" : "sub-category", // под категория
            "childs" : [ 
        {
          "_id" : ObjectId("33b55aa654bce61356002559"),
          "name" : "sub-sub-category", //Категория третьего уровня
          "childs": ""
        }
      ]
        }
    ]
}

I need to get a sub category.
$category = Categories::findOne(['childs._id' => $id]) -> childs;
foreach ($category as $cat);
$cat['name'];

But how do I get a third level category?
$category = Categories::findOne(['childs._id' => $id]) -> childs;
foreach ($category as $cat);
foreach ($cat as $c);
$c['name'];

But after all, there can be as many levels as you like, and it’s somehow wrong to write a method for each.
Can this be optimized somehow?
Thank you.

Answer the question

In order to leave comments, you need to log in

1 answer(s)
A
Alexander Aksentiev, 2017-03-29
@sharomet

recursion is called

Didn't find what you were looking for?

Ask your question

Ask a Question

731 491 924 answers to any question