关于简单 MongoDB 数据库结构的建议
我刚刚开始使用 MongoDB 和 Mongoid for Rails,需要一些关于设计简单博客数据库的正确方法的建议。
我目前正在使用下面的结构,但我需要一种方法来查询给定用户编写的所有评论(关系数据库等效项为 Comment.where('user_id = ?', user_id)
) 。
这是正确的设置,还是我应该将注释移到他们自己的文档中,而不是将它们嵌入到帖子中(就像我在关系数据库模式中一样)?
感谢任何建议,谢谢。
数据库架构
post {
_id: (object id)
title: string
body: string
user_id: reference
comments: [
{ _id: (object id), body: string, user_id: reference },
{ _id: (object id), body: string, user_id: reference },
...
]
}
user {
_id: (object id)
name: string
}
在MongoDB中,我对应的模型是:
class Post
include Mongoid::Document
field :title
field :body
embeds_many :comments
references_one :user
end
class Comment
include Mongoid::Document
field :body
embedded_in :post
references_one :user
end
class User
include Mongoid::Document
field :name
references_many :posts
end
I'm just getting started with MongoDB and Mongoid for Rails and in need of some advice on the right way to design a simple blog database.
I'm currently using the structure below, but I need a way to query all comments written by a given user (the relational db equivalent would be Comment.where('user_id = ?', user_id)
).
Is this the right set up, or should I move comments out into their own document, and not embed them in posts (as I would in a relational db schema)?
Appreciate any advice, thanks.
Database Schema
post {
_id: (object id)
title: string
body: string
user_id: reference
comments: [
{ _id: (object id), body: string, user_id: reference },
{ _id: (object id), body: string, user_id: reference },
...
]
}
user {
_id: (object id)
name: string
}
In MongoDB, my corresponding models are:
class Post
include Mongoid::Document
field :title
field :body
embeds_many :comments
references_one :user
end
class Comment
include Mongoid::Document
field :body
embedded_in :post
references_one :user
end
class User
include Mongoid::Document
field :name
references_many :posts
end
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(3)
Mongodb.org 上有一篇很棒的文章,介绍了建模注释的各种选择。
查看:http://www.mongodb。 org/display/DOCS/MongoDB+Data+Modeling+and+Rails#MongoDBDataModelingandRails-ModelingComments
There's a great article on Mongodb.org about the various choices for modeling comments.
Check out: http://www.mongodb.org/display/DOCS/MongoDB+Data+Modeling+and+Rails#MongoDBDataModelingandRails-ModelingComments
您可以在 MongoDB 中使用点表示法对嵌入文档运行查询过滤器。
在您的情况下,要检索用户的所有评论,您可以简单地执行以下操作:
You can use dot-notation in MongoDB to run query filters against embedded documents.
In your case, to retrieve all comments by a user, you could simply do:
http://www.mongodb.org/display/DOCS /Dot+Notation+(Reaching+into+Objects)
但不确定您真正需要多少种不同的选项。
可以选择嵌入文档或多个查询或数据库引用。
不知道为什么必须一遍又一遍地问这个问题。
http://www.mongodb.org/display/DOCS/Dot+Notation+(Reaching+into+Objects)
But not sure how many different options you really need.
Embedded docs or multiple queries or database references are options.
Not sure why this must be asked over and over again.