Can a MongoDB collection have inside it another collection?

I need to store a recursive tree structure. A linked list. So all the objects are the same. Each has a pointer to a parent object and each has an array of child objects. Can I store such a structure in Mongo. i.e. A Mongo collection of parent objects, each object holds within it a Mongo collection of child objects.

$a = $MyCollection->findOne(**some conditions)->Childs->find(...)


You cant store collections in collections. But you can store ids that reference objects in other collections. You would have to resolve the id to the document or element and then if that element stores more ids you would need to resolve those on and on. Documents are meant to be rich and duplicate data but in the docs they do explain that instead of embedding you can just use ids

MongoDB can store subdocuments:

    "value" : "root"
    "children" : [ { "value" : "child1", "children" : [ ... ] }, 
                   { "value" : "child2", "children" : [ ... ] } ]

However, I don't recommend to use subdocuments for tree structures or anything that is rather complex. Subdocuments are not first-level citizens; they are not collection items.

For instance, suppose you wanted to be able to quickly find the nodes with a given value. Through an index on value, that lookup would be fast. However, if the value is in a subdocument, it won't be indexed because it is not a collection element's value.

Therefore, it's usually better to do the serialization manually and store a list of ids instead:

  "_id" : ObjectId("..."),
  "parentId" : ObjectId("..."), // or null, for root

You'll have to do some of the serialization manually to fetch the respective element's ids.

Hint Suppose you want to fetch an entire branch of the tree. Instead of storing only the direct parent id, you can store all ancestor ids instead:

"ancestorIds": [id1, id2, id3]

Need Your Help

VS2010 how to make output to show counter of projects built

windows visual-studio-2010 visual-studio csc

I have solution with very big number of projects in it and would like to see somehow progress of compilation.

Android GoogleMaps v2 Scroll limit

android android-maps-v2

I have offline map implemented on GoogleMap (tilesOverly) Everything working fine just the problem is i can scroll outside the offline map.

About UNIX Resources Network

Original, collect and organize Developers related documents, information and materials, contains jQuery, Html, CSS, MySQL, .NET, ASP.NET, SQL, objective-c, iPhone, Ruby on Rails, C, SQL Server, Ruby, Arrays, Regex, ASP.NET MVC, WPF, XML, Ajax, DataBase, and so on.