Can a MongoDB collection have inside it another collection?

后端 未结 2 1052
情歌与酒
情歌与酒 2021-01-02 02:01

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.

2条回答
  •  迷失自我
    2021-01-02 02:55

    MongoDB can store subdocuments:

    Node
    {
        "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:

    Node 
    {
      "_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]

提交回复
热议问题