有效检查文档是否有子文档


Efficiently check if document has children

我正在尝试使用Doctrine MongoDB构建一个惰性加载树。我的文档结构如下:

/**
 * @ODM'Document(repositoryClass="CmsPage'Repository'PageRepository")
 */
class Page
{
    /**
     * @ODM'String
     * @var string
     */
    protected $title;
    /**
     * @ODM'ReferenceOne(targetDocument="CmsPage'Document'Page", inversedBy="children")
     * @ODM'Index
     * @var Page
     */
    protected $parent;
    /**
     * @ODM'ReferenceMany(
     *     targetDocument="CmsPage'Document'Page", mappedBy="parent",
     *     sort={"title": "asc"}
     * )
     * @var array
     */
    protected $children;
    /**
     * Default constructor
     */
    public function __construct()
    {
        $this->children = new ArrayCollection();
    }
    /**
     * @return ArrayCollection|Page[]
     */
    public function getChildren()
    {
        return $this->children;
    }
    /**
     * @param ArrayCollection $children
     */
    public function setChildren($children)
    {
        $this->children = $children;
    }
    /**
     * @return Page
     */
    public function getParent()
    {
        return $this->parent;
    }
    /**
     * @param Page $parent
     */
    public function setParent($parent)
    {
        $this->parent = $parent;
    }
    /**
     * @return string
     */
    public function getTitle()
    {
        return $this->title;
    }
    /**
     * @param string $title
     */
    public function setTitle($title)
    {
        $this->title = $title;
    }
}

以下代码将检索给定页面的所有子项:

$page = $pageRepo->find('foo');
$children = [];
foreach ($page->getChildren() as $childPage) {
    $children[] = [
        'id' => $childPage->getId(),
        'slug' => $childPage->getSlug(),
        'leaf' => ($childPage->getChildren()->count() == 0)
    ];

这按预期工作,但将为每个子页面执行单独的查询以检查它是否是叶子。当处理具有许多子节点的大树时,效率不高。

我可以在我的 Page 文档中引入布尔isLeaf,并在持久化时对其进行更新。但这也意味着我在添加或删除孩子时必须更新父级。

你有什么指示来解决这个问题吗?

我知道在MongoDB中测试数组不为空的最有效方法是使用"点表示法"和$exists搜索数组中"第一个"元素的存在。查询构建器中对此有访问权限:

$qb = $dm->createQueryBuilder('Page')
    ->field('children.0')->exists(true);

这与外壳中的相同:

db.collection.find({ "children.0": { "$exists": true } })

因此0是数组中第一个元素的索引,并且仅在该数组中存在某些内容时才存在。空数组不符合此条件。