开发者

Retrieving an embedded document

If I had a document called Category, which embeds many SubCategory documents... what's the best way to retrieve a SubCategory (for example based on ID).

This doesn't work using a DocumentRepository. I am aware that this is a present limitation of MongoDB and I've alrea开发者_如何学JAVAdy voted on virtual collections.

So I'm wondering what the best way to retrieve a SubCategory is. My current approach looks like this:

<?php

$category = $dm->createQueryBuilder('Category')
                ->field('subCategories._id', new \MongoId($id))
            ->getQuery()->getSingleResult();

foreach($category->getSubCategories() as $sub){
    if($sub->getId() === $id){
        $subCategory = $sub;
        break;
    }
}


So the nature of MongoDB is that you cannot return "sub-documents" independently of their parent documents. So when retrieving a sub-category, you'll have to pull back the parent category and then loop through to find the sub-object.

This type of looping is more common when nesting in MongoDB. Because you're getting whole documents, you have to be prepared to "drill down" a little. Typically this involves writing some small helper methods like the one you've written.

The code you presented seems completely reasonable. In PHP, I would strongly suggest wrapping this up in a method on an appropriate Object, something like Category::GetSubCategory($id).

0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜