Best way to get embedded documents in pymongo?

In my MongoDB docs 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” are an array with other documents. Now I can request this document with the name of the page, and I will receive a complete document with all pages and other information. I use pymongo directly in python to request a document, but now I don’t know how best to get the page from the pages of the array. 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 separate page or a common inline document? All hints or code snippets are welcome.

Thanks! Jarus

+4
source share
2 answers

Yes you are right. In mongodb, you cannot load an embedded document without a parent. You can load the parent document using some property of the 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 over all attached documents to the search page that you need.

If you often need to download an embedded document, you need to reconfigure your database (move the pages to the root collection, but it seems to me that everything is fine with your schema).

+2
source

Read Obtaining a subset of fields on the mongodb website.

I hope this helps you.

0
source

Source: https://habr.com/ru/post/1342428/


All Articles