开发者

The best way to get embedded documents in pymongo?

I has in MongoDB documents like this:

{
"user": ObjectID("4d71076b26ab7b032800009f")
"pages" : [
    {
        "name" : "Main",
        "content" : [
            {
                "id" : ObjectId("4d71076b26ab7b052800009f")
            },
            {
                "id" : ObjectId("4d61269b1deb5a3fce000004"),
                "link" : "http://example.com"
            }
        ]
    }
]}

You can see that the key "pages" is a array with other documents. Now I can query this document with the name of a p开发者_如何学JAVAage and I will get the full document with all pages and other information. I use in python directly pymongo to query the document but now I don't know what the best way is to get a page from the array pages. I think something like this:

def getPage(pageNameWhoINeed):
    for page in pages:
        if page['name'] == pageNameWhoINeed:
           return page

But is this the best way to get a singe page or general a embedded document? All tipps or code snippets are welcome.

Thanks! Jarus


Yes you are right. In mongodb you can't load embedded document without parent. You can load parent document by some property of child document.

pages.find({"pages.name", "Main"}); //should load all document that contains pages  collection and at least one item in embedded collection with name 'Main'.

Than you need to iterate through all embedded documents an find page that you need.

If you often need to load embedded document, mb you need to redesign your database(move pages to the root collection, but it seems to me that all okay with your schema).


Please read Retrieving a Subset of Fields on the mongodb website.

I hope that it will help you.

0

上一篇:

下一篇:

精彩评论

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

最新问答

问答排行榜