MongoDB 多对多关联 [英] MongoDB Many-to-Many Association
问题描述
您将如何与 MongoDB 进行多对多关联?
How would you do a many-to-many association with MongoDB?
例如;假设您有一个用户表和一个角色表.用户有很多角色,角色有很多用户.在 SQL 域中,您将创建一个 UserRoles 表.
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
在 MongoDB 中如何处理同类关系?
How is same sort of relationship handled in MongoDB?
推荐答案
根据您的查询需求,您可以将所有内容放入用户文档中:
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" } );
如果您想在单独的文档中维护角色,那么您可以在角色数组中包含文档的 _id 而不是名称:
If you want to maintain the roles in separate documents then you can include the document's _id in the roles array instead of the name:
{name:"Joe"
,roles:["4b5783300334000000000aa9","5783300334000000000aa943","6c6793300334001000000006"]
}
并设置如下角色:
{_id:"6c6793300334001000000006"
,rolename:"Engineer"
}
这篇关于MongoDB 多对多关联的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!