我很难理解如何在像MongoDB这样的软模式中强制执行嵌入式文档。如果给出这样的数据模型:
User{
UserId:
Email:
Phone:
Reviews{
Rating:
Comment:
}//End reviews
}
这是否意味着每个用户文档只有一个评论,或者这是用户所有评论的格式?
也许更多的关系模型可能就是这样:
User{
UserId:
Phone:
Email:
}
Reviews{
User:<UserID>
Rating:
Comment:
}
我知道使用引用意味着查询速度较慢,但我不明白嵌入式文档如何允许多次审核。
答案 0 :(得分:1)
您是在谈论如何在MongoDB或像Mongoose这样的ODM中强制执行此操作?对于MongoDB,答案很简单:MongoDB没有强制执行架构。您可以在MongoDB集合中包含以下所有三个文档:
{
"reviews" : {
"rating" : 9001,
"comment" : "nice scenery"
}
}
{
"reviews" : [
{
"rating" : [2, 4, 5],
"comment" : 19
},
{
"rating" : -845,
"comment" : "Powerful stuff"
}
]
}
{
"reviews" : "no"
}
在强制执行架构应用程序端的ODM中,您的符号最接近于意味着每个文档应该有一个reviews
子文档的内容。
答案 1 :(得分:1)
如果同一个用户拥有多个文档,MongoDB会在每次添加新文档时为文档添加一个唯一的_Id,因此当您为同一个用户添加多个文档时,以及@wdberkeley所说的这个文件很好,MongoDB不强制执行架构,
"User" {
"UserId": "johndoe"
"Email": "johndoe@yahoo.com"
"Phone": "555-44444"
"Review"{
"Rating": "5"
"Comment": "this is my first comment"
}
}
"User" {
"UserId": "johndoe"
"Email": "johndoe@yahoo.com"
"Phone": "555-44444"
"Review"{
"Rating": "5"
"Comment": "this is my second comment"
}
}
"User" {
"UserId": "johndoe"
"Email": "johndoe@yahoo.com"
"Phone": "555-44444"
"Review"{
"Rating": "5"
"Comment": "this is my third comment"
}
}
如果一个文档针对一个具有多个评论的用户,这也可以正常工作,可以随时获取文档并添加附加评论并在文档上调用db.update(),
"User" {
"UserId": "johndoe"
"Email": "johndoe@yahoo.com"
"Phone": "555-44444"
"Reviews"{[
{
"Rating": "5"
"Comment": "this is my first comment"
},
{
"Rating": "5"
"Comment": "this is my second comment"
},
{
"Rating": "5"
"Comment": "this is my third comment"
}
]}
}