Can a MongoDB collection have inside it another collection?

岁酱吖の 提交于 2019-11-30 18:19:35

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:

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]

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!