【发布时间】:2019-11-18 19:26:39
【问题描述】:
我有 3 张桌子考虑 1。用户表 用户名、电子邮件、用户 ID、对象 ID 2。角色表 对象ID、角色ID、角色名称 3。用户角色表 对象ID、角色ID、用户ID
我需要使用猫鼬的用户细节 用户名、电子邮件、用户 ID、角色名 需要解决方案
【问题讨论】:
我有 3 张桌子考虑 1。用户表 用户名、电子邮件、用户 ID、对象 ID 2。角色表 对象ID、角色ID、角色名称 3。用户角色表 对象ID、角色ID、用户ID
我需要使用猫鼬的用户细节 用户名、电子邮件、用户 ID、角色名 需要解决方案
【问题讨论】:
db.users.aggregate([
// Join with user_info table
{
$lookup:{
from: "user_role",
localField: "userId",
foreignField: "userId",
as: "user_role"
}
},
{ $unwind:"$user_role" }, // $unwind used for getting data in object or for one record only
// Join with user_role table
{
$lookup:{
from: "role",
localField: "roleId",
foreignField: "roleId",
as: "user_role"
}
},
{ $unwind:"$role" },
// define some conditions here
{
$match:{
$and:[{"userid" :1}]
}
},
// define which fields are you want to fetch
{
$project:{
_id : 1,
email : 1,
userName : 1,
userPhone : "$user_info.phone",
role : "$user_role.role",
}
}
])
【讨论】: