It seems like, with your current data model, that you would need to retrieve the top level document and then recursively search for the object you want inside of the document you retrieved.
There are many ways to store hierarchical data and I would suggest you take a look at the 10gen docs here, they are pretty thorough but I will summarize for you below.
Let's take a look at some of the ideas presented in that document starting with the good parts and drawbacks to your current approach.
Full Tree in Single Document (What you are doing now)
- Pros:
- Single document to fetch per page
- One location on disk for whole tree
- You can see full structure easily
- Cons
- Hard to search
- Hard to get back partial results
- Can get unwieldy if you need a huge tree. Further there is a limit on the size of documents in MongoDB – 16MB in v1.8 (limit may rise in future versions).
Your question relates directly to the problem of searching so, depending on your use case and desire to optimize, you probably either want to take the Array of Ancestors or the Materialized Path approach instead.
Array of Ancestors
With this approach you would store the ancestors of a document in an array and create an index on that field so that it was quickly and easily searchable.
Materialized Path
With this approach you would store the full path to the document as a string of ancestors and query via regular expression.
Make sense?
_id
andname
at unknown depth in that tree-like document? – KL-7