MongoDB:具有嵌入式文档的高效模式设计
我对 NoSQL 非常陌生,我正在尝试了解它。作为一个例子,我试图为一个简单的博客设计一个模式,该博客的作者有帖子,有评论。就像这样:
Author
name : String,
email : String,
posts : [Post]
Post
title : String,
body : String,
comments : [Comment]
Comment
commenter : String,
comment : String
所以这似乎是设计模式的最非规范化的方式。当我想获取作者帖子列表时,它非常有用,但是当我尝试按标题查询帖子时,我遇到了问题。这将返回作者对象和该作者的所有帖子。然后我可以在帖子中搜索我想要的帖子,但这似乎效率很低。
处理这种模式最有效的方法是什么?我应该只有一个 Posts 对象并将作者设置为 Post 对象中的字段(或嵌入文档)吗?或者也许最好将数据存储在多个位置?
我花了很多年尝试规范关系数据库,但我似乎无法以 NoSQL 方式思考。任何建议将不胜感激。
I'm very new to NoSQL and I'm trying to wrap my head around it. As an example I am trying to design a schema for a simple blog that has authors who have posts, which have comments. Like so:
Author
name : String,
email : String,
posts : [Post]
Post
title : String,
body : String,
comments : [Comment]
Comment
commenter : String,
comment : String
So this seems to be the most de-normalized way to design the schema. It works great when I want to get a list of an authors posts, but I run into problems when I try to query a post by it's title. This returns the author object and all that author's posts. I can then search the posts for the one I want, but that seems inefficient.
What is the most efficient way to handle this kind of schema? Should I only have a Posts object and make the author a field (or embedded doc) in the Post object? Or perhaps it's best to store the data in multiple locations?
I've spent so many years trying to normalize relational databases that I can't seem to think in the NoSQL way. Any advice would be appreciated.
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(2)
如果这里模型的“核心”是帖子,那么为什么不做到这一点,第一。您可以按标题、作者和日期搜索帖子。
If the 'core' of your model here is the post then why not make it so, Number One. You can search posts by title, by author and by date.
非规范化并不意味着禁止外键。
我认为你绝对应该通过 ID 引用你的作者。但是,这就是非规范化的用武之地,您希望将作者姓名存储在
Author
中,和 中的Post
对象中。这样,您就不需要加入Author
和Post
集合。Denormalization does not mean foreign keys are forbidden.
I think you should definitely have a reference to your author by Id. However, and that is where denormalization comes in, you want to store the author name in the
Author
and in thePost
objects. This way, you don't need to join theAuthor
andPost
collections.