MongoDB嵌套集 [英] MongoDB nested sets
问题描述
在MongoDB中存储嵌套集(如注释树)的最佳实践是什么?
What're the best practices to store nested sets (like trees of comments) in MongoDB?
我的意思是,每个评论都可以有一个父评论和一个子评论(答案).
I mean, every comment can have a parent comment and children-comments (answers).
像这样存储它们:
{
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" },
]
}
并不酷,因为例如,我们不能在没有地图/缩小的情况下索取彼得发表评论的所有帖子".
is not cool, because we can't, for example, ask for "all post which are commented by Peter" without map/reduce.
推荐答案
我认为没有完美的解决方案-取决于哪些操作对您的应用更为重要.我认为,例如Silicon Alley Insider会存储嵌套在MongoDB中的注释.这确实使您提到的查询更加困难.
I think there is no perfect solution - depends on what operations are more important for your app. I believe Silicon Alley Insider stores comments nested with MongoDB for example. That does make the query you mention harder.
一个选项存储在帖子的顶层,其中包含数组中所有评论者的列表.可以将其视为非规范化数据.这样一来,您可以轻松找到涉及某个评论者的所有帖子.然后向下钻取,您可以使用map/reduce或db.eval()来获取嵌套的帖子信息.
One option is store at top-level in the post a list of all commenters in an array. Think of that as denormalized data. Then one can easily find all posts which involve a certain commenter. Then to drill down, you use map/reduce or db.eval() to get the nested post info within.
另一个注意事项-如果要处理单个文档,则db.eval()的重量可能比map/reduce的重量轻. $ where也是一个选项,但可能会很慢,因此我喜欢上面提到的其他评论者列表"-也不容易为该数组建立索引(请参见文档中的"Multikey").
One other note - if you are dealing with a single document, db.eval() is probably lighter-weight than map/reduce. $where is also an option but can be slow so I like the additional 'list of commenters' mentioned above - not it is also easy to index that array too (see 'Multikey' in the docs).
这篇关于MongoDB嵌套集的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!