如何在mongodbmo中建立多对多的关系

时间:2015-07-08 06:03:07

标签: mongodb

我刚开始学习MongoDB。 有人可以提供一些关于如何用mongodb实现这个例子的东西吗?

示例

# Here are my categories
> hmset category:1 name cinema  ... more fields ...
> hmset category:2 name music   ... more fields ...
> hmset category:3 name sports  ... more fields ...
> hmset category:4 name nature  ... more fields ...

# Here are my users
> hmset user:1 name Jack   ... more fields ...
> hmset user:2 name John   ... more fields ...
> hmset user:3 name Julia  ... more fields ...

# Let's establish the many-to-many relationship
# Jack likes cinema and sports
# John likes music and nature
# Julia likes cinema, music and nature

# For each category, we keep a set of reference on the users
> sadd category:1:users 1 3
> sadd category:2:users 2 3
> sadd category:3:users 1
> sadd category:4:users 2 3

# For each user, we keep a set of reference on the categories
> sadd user:1:categories 1 3
> sadd user:2:categories 2 4
> sadd user:3:categories 1 2 4

1 个答案:

答案 0 :(得分:0)

在MongoDB中,您可以选择预先加入数据,因此可以将文档放在:

user : "John",
categories : ["music", "nature"]

还可以选择放置引用(更像是RDBMS):

user : "John",
categories : [    ObjectId("1e222222222"),
                  ObjectId("2e333333") ]

这基本上取决于您的数据访问模式。所以,如果您基本上只是检索与用户相关联的类别,那么第一种情况应该没问题,否则您可以考虑第二种情况为用户和类别设置不同的集合,然后引用它们,如下所示:< / p>

var category = { _id: "music"
            , name: "Musical Category"
            , users: ["jack", "julia", "john"] }
var user = { _id: "jack", name: "Jack", categories: ["music"]}
db.categories.save(category)
db.users.save(user)

db.categories.find({_id: {$in: user.categories}}) // categories for user
db.users.find({_id: {$in: category.users}}) // users for category

但我刚刚触及了架构设计的主题。您必须分析基数和数据访问模式才能获得可靠的设计。 来自Mongo的帖子给出了非常好的解释和示例: http://blog.mongodb.org/post/87200945828/6-rules-of-thumb-for-mongodb-schema-design-part-1

来自手册:http://docs.mongodb.org/manual/applications/data-models/