如何在MongoDB中组织多对多关系 [英] How to organise a many to many relationship in MongoDB

查看:162
本文介绍了如何在MongoDB中组织多对多关系的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我有两个表/集合;用户和组.用户可以是任意数量的组的成员,而用户也可以是任意数量的组的所有者.在关系数据库中,我可能会有一个名为UserGroups的第三个表,其中有一个UserID列,一个GroupID列和一个IsOwner列.

I have two tables/collections; Users and Groups. A user can be a member of any number of groups and a user can also be an owner of any number of groups. In a relational database I'd probably have a third table called UserGroups with a UserID column, a GroupID column and an IsOwner column.

我正在使用MongoDB,并且我确定在文档数据库中针对这种关系有另一种方法.我应该将用户组"列表和所有者分组"列表作为两个ObjectID数组嵌入到用户表中吗?我是否还应该将组"表中的成员和所有者列表存储为两个数组,以有效地镜像关系,从而导致关系信息重复?

I'm using MongoDB and I'm sure there is a different approach for this kind of relationship in a document database. Should I embed the list of groups and groups-as-owner inside the Users table as two arrays of ObjectIDs? Should I also store the list of members and owners in the Groups table as two arrays, effectively mirroring the relationship causing a duplication of relationship information?

桥接用户组表是文档数据库中多对多关系的合法概念吗?

Or is a bridging UserGroups table a legitimate concept in document databases for many to many relationships?

谢谢

推荐答案

我所看到的事情以及我目前使用的是每个文档中带有节点ID的嵌入式数组.

What I've seen done, and what I currently use are embedded arrays with node id's in each document.

因此,文档user1具有属性组:[id1,id2]

So document user1 has property groups: [id1,id2]

文档组1具有属性用户:[user1].文档组2还具有属性用户:[user1].

And document group1 has property users: [user1]. Document group2 also has property users: [user1].

通过这种方式,您可以获得组对象并轻松选择所有相关用户,并且该用户也相同.

This way you get a Group object and easily select all related users, and the same for the User.

在创建和更新对象时,这需要做更多的工作.当您说两个对象相关时,您必须更新两个对象.

This takes a bit more work when creating and updating the object. When you say 2 objects are related, you have to update both objects.

MongoDB中还有一个DBReferences概念,根据您的驱动程序,它会在检索文档时自动提取引用的对象.

There's also a concept DBReferences in MongoDB and depending on your driver, it'll pull referenced objects automatically when retrieving a document.

http://www.mongodb.org/display/DOCS/Database + References#DatabaseReferences-DBRef

这篇关于如何在MongoDB中组织多对多关系的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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