How to organise a many to many relationship in MongoDB

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

Leave a Comment