Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
281 views
in Technique[技术] by (71.8m points)

How to organise a many to many relationship in MongoDB

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.

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?

Thanks

See Question&Answers more detail:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Reply

0 votes
by (71.8m points)

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

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

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.

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


与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
OGeek|极客中国-欢迎来到极客的世界,一个免费开放的程序员编程交流平台!开放,进步,分享!让技术改变生活,让极客改变未来! Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

Just Browsing Browsing

[4] html - How to create even cell spacing within a

1.4m articles

1.4m replys

5 comments

57.0k users

...