MongoDB:具有嵌入式文档的高效模式设计 [英] MongoDB: Efficient schema design with embedded documents

查看:37
本文介绍了MongoDB:具有嵌入式文档的高效模式设计的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我对 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.

处理这种模式的最有效方法是什么?我应该只有一个 Posts 对象并使作者成为 Post 对象中的一个字段(或嵌入的文档)吗?或者最好将数据存储在多个位置?

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?

我花了这么多年试图规范关系数据库,但我似乎无法以 NoSQL 的方式思考.任何建议将不胜感激.

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.

推荐答案

非规范化并不意味着禁止外键.

Denormalization does not mean foreign keys are forbidden.

我认为您绝对应该通过 Id 引用您的作者.但是,这就是非规范化的用武之地,您希望将作者姓名存储在 Author 中的 Post 对象中.这样,您就不需要加入 AuthorPost 集合.

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 the Post objects. This way, you don't need to join the Author and Post collections.

Post
  title: string
  body: string
  authorName: string
  authorId: [id of author]
  comments: list of [Comment]
  created: date
  modified: date

Author
  name: string
  email: string

Comment
  subject: string
  body: string
  author: string (if you want anon comments)

这篇关于MongoDB:具有嵌入式文档的高效模式设计的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆