4

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 page 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

4

2 回答 2

2

是的你是对的。在 mongodb 中,您无法加载没有父级的嵌入文档。您可以通过子文档的某些属性加载父文档。

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

比您需要遍历所有嵌入文档来查找所需的页面。

如果您经常需要加载嵌入式文档,mb 您需要重新设计数据库(将页面移动到根集合,但在我看来,您的架构一切正常)。

于 2011-03-05T16:26:45.920 回答
0

请阅读mongodb 网站上的检索字段子集。

我希望它会帮助你。

于 2011-03-09T09:59:59.167 回答