MongoDB的许多-to-many关联 [英] MongoDB Many-to-Many Association
问题描述
你会怎么做一个多到很多协会的MongoDB?
How would you do a many-to-many association with MongoDB?
例如;假设你有一个用户表和角色表。用户有很多角色和角色有许多用户。在SQL的土地,你将创建一个表的UserRole
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的许多-to-many关联的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!