Can a MongoDB collection have another collection in it?

I need to maintain a recursive tree structure. Linked List.
Thus, all objects are the same. Each of them has a pointer to the parent object, and each of them has an array of child objects.
Can I keep such a structure in Mongo. those. A Mongolian collection of parent objects, each object holds in it a collection of Mongo child objects.

$a = $MyCollection->findOne(**some conditions)->Childs->find(...) 
+6
source share
2 answers

You cannot store collections in collections. But you can store identifiers that reference objects in other collections. You will have to resolve the identifier of the document or element, and then if this element stores more identifiers, you will need to resolve them. Documents are intended for rich and duplicate data, but in documents that they explain, instead of embedding, you can simply use identifiers

+3
source

MongoDB can store subdocuments:

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

However, I do not recommend using subdocuments for tree structures or something rather complicated. Subdocuments are not first-level citizens; they are not elements of the collection.

For example, suppose you want to quickly find nodes with a given value. Through the value index, this search will be fast. However, if the value is in a subdocument, it will not be indexed because it is not the value of a collection item.

Therefore, it is usually better to serialize manually and instead keep a list of identifiers:

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

You will need to manually serialize to get the corresponding item IDs.

Tip Suppose you want to get the whole branch of a tree. Instead of storing only the direct parent identifier, you can save all the ancestor identifiers:

"ancestorIds": [id1, id2, id3]

+5
source

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


All Articles