Trees ===== MongoDB lends itself quite well to storing hierarchical data. This chapter will demonstrate some examples! Full Tree in Single Document ---------------------------- .. code-block:: php createQueryBuilder('BlogPost') ->selectSlice('replies', 0, 10) ->getQuery() ->getSingleResult(); $replies = $post->getReplies(); You can read more about this pattern on the MongoDB documentation page "Trees in MongoDB" in the `Full Tree in Single Document `_ section. Parent Reference ---------------- .. code-block:: php createQueryBuilder('Category') ->field('parent.id')->equals('theid') ->getQuery() ->execute(); You can read more about this pattern on the MongoDB documentation page "Trees in MongoDB" in the `Parent Links `_ section. Child Reference --------------- .. code-block:: php createQueryBuilder('Category') ->field('id')->equals('theid') ->getQuery() ->getSingleResult(); $children = $category->getChildren(); Query for immediate parent of a category: .. code-block:: php createQueryBuilder('Category') ->field('children.id')->equals('theid') ->getQuery() ->getSingleResult(); You can read more about this pattern on the MongoDB documentation page "Trees in MongoDB" in the `Child Links `_ section. Array of Ancestors ------------------ .. code-block:: php createQueryBuilder('Category') ->field('ancestors.id')->equals('theid') ->getQuery() ->execute(); Query for all ancestors of a category: .. code-block:: php createQuery('Category') ->field('id')->equals('theid') ->getQuery() ->getSingleResult(); $ancestors = $category->getAncestors(); You can read more about this pattern on the MongoDB documentation page "Trees in MongoDB" in the `Array of Ancestors `_ section. Materialized Paths ------------------ .. code-block:: php createQuery('Category') ->sort('path', 'asc') ->getQuery() ->execute(); Query for the node 'b' and all its descendants: .. code-block:: php createQuery('Category') ->field('path')->equals('/^a,b,/') ->getQuery() ->execute(); You can read more about this pattern on the MongoDB documentation page "Trees in MongoDB" in the `Materialized Paths (Full Path in Each Node) `_ section.