MongoDB 集合中可以包含另一个集合吗?
我需要存储递归树结构。一个链接列表。
所以所有的对象都是一样的。每个都有一个指向父对象的指针,每个都有一个子对象数组。
我可以在 Mongo 中存储这样的结构吗?
即父对象的 Mongo 集合,每个对象中都包含子对象的 Mongo 集合。
$a = $MyCollection->findOne(**some conditions)->Childs->find(...)
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(...)
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。

绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(2)
您无法将集合存储在集合中。但是您可以存储引用其他集合中的对象的 id。您必须将 id 解析为文档或元素,然后如果该元素存储更多 id,您将需要不断地解析这些 id。文档应该是丰富且重复的数据,但在文档中,他们确实解释说,您可以只使用 ids 而不是嵌入
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 可以存储子文档:
但是,我不建议将子文档用于树结构或任何相当复杂的内容。子文档不是一级公民;它们不是收藏品。
例如,假设您希望能够快速找到具有给定值的节点。通过
value
上的索引,查找速度会很快。但是,如果该值位于子文档中,则不会对其进行索引,因为它不是集合元素的值。因此,通常最好手动执行序列化并存储 id 列表:
您必须手动执行一些序列化才能获取相应元素的 id。
提示
假设您想获取树的整个分支。您可以存储所有祖先 ID,而不是仅存储直接父 ID:
"ancestorIds": [id1, id2, id3]
MongoDB can store subdocuments:
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:
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]