在MongoDB中存储嵌套集(如注释树)的最佳实践是什么?
我的意思是,每个评论都可以有父评论和孩子评论(答案).
像这样存储它们:
{
title: "Hello",
body: "Please comment me!",
comments: [
{
author: "Peter",
text: "Hi there",
answers: [
{
author: "Peter",
text: "Hi there",
answers: [
{ author: "Ivan", text: "Hi there" },
{ author: "Nicholas", text: "Hi there" }
]
},
{ author: "Ivan", text: "Hi there" },
{ author: "Nicholas", text: "Hi there" },
]
},
{ author: "Ivan", text: "Hi there" },
{ author: "Nicholas", text: "Hi there" },
]
}
Run Code Online (Sandbox Code Playgroud)
并不酷,因为我们不能,例如,在没有map/reduce的情况下,请求"所有被Peter评论的帖子".
我认为没有完美的解决方案 - 取决于哪些操作对您的应用程序更重要。例如,我相信 Silicon Alley Insider 存储嵌套在 MongoDB 中的评论。这确实使您提到的查询变得更加困难。
一种选择是在帖子的顶层存储数组中所有评论者的列表。将其视为非规范化数据。然后,人们可以轻松找到涉及某一评论者的所有帖子。然后,为了向下钻取,您可以使用 map/reduce 或 db.eval() 来获取其中的嵌套帖子信息。
另请注意 - 如果您正在处理单个文档,则 db.eval() 可能比 map/reduce 更轻。$where 也是一个选项,但可能很慢,所以我喜欢上面提到的附加“评论者列表” - 索引该数组也很容易(请参阅文档中的“Multikey”)。
| 归档时间: |
|
| 查看次数: |
7497 次 |
| 最近记录: |