views:

708

answers:

1

How would you do a many-to-many association with MongoDB?

For example; let's say you have a Users table and a Roles table. Users have many roles, and roles have many users. In SQL land you would create a UserRoles table.

Users:
    Id
    Name

Roles:
    Id
    Name

UserRoles:
    UserId
    RoleId

How is same sort of relationship handled in MongoDB?

+3  A: 

Depending on your query needs you can put everything in the user document:

{name:"Joe"
,roles:["Admin","User","Engineer"]
}

To get all the Engineers, use:

db.things.find( { roles : "Engineer" } );

If you want to maintain the roles in separate documents then you can the document's _id in the roles array instead of the name:

{name:"Joe"
,roles:["4b5783300334000000000aa9","5783300334000000000aa943","6c6793300334001000000006"]
}

and set up the roles like:

{_id:"6c6793300334001000000006"
,rolename:"Engineer"
}
Diederik Hoogenboom
The latter would be better since I need to get a list of all available roles. The only bad part is I need to setup both ends of the association then. When doing the SQL way, adding a UserRole will make the User know about the Role and the Role know about the User. This way means I'll have to set the Role on the User, and the User on the Role. I guess that's fine though.
Josh Close
sounds relational. You might want to use a relational DB...
DanInDC

related questions