0
votes

As I can get specific field values ​​by querying with MongoId a document whose structure is as follows:

{
    _id: ObjectId(xxx),
    name: xxx,
    subs: [{
        _id: ObjectId(yyy),
        name: yyy,
        subs: [{
            _id: ObjectId(zzz),
            name: zzz,
            subs: [...]
        }]
    }]
}

I need that, given a specific ObjectId obtaining an element that have the fields: _id, name

Note: a single document with all information.

regards

2
I'm using versions mongoid 2.0.2, rails 3.1, ruby 1.9.2 and mongodb 1.6.6.lordmkichavi
I'm sorry, but I didn't get what exactly you want. Do you want to find an embedded document by _id and name at unknown depth in that tree-like document?KL-7

2 Answers

1
votes

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?

1
votes

If you are building a tree structure in mongoid. I would suggest looking into Mongoid Tree

it's nice gem that would give you all or a least most of things you need.

From Read Me:

class Node
  include Mongoid::Document
  include Mongoid::Tree
end



Node.root
Node.roots
Node.leaves
node.root
node.parent
node.children
node.ancestors
node.ancestors_and_self
node.descendants
node.descendants_and_self
node.siblings
node.siblings_and_self
node.leaves