如何在MongoDB中合并多个集合

时间:2019-12-03 12:37:02

标签: mongodb collections

我有三个集合(“角色”,“权限”,“角色权限”)。在这种情况下,我想列出所有权限(collection-> permission),但我也想添加角色信息并添加一个来自role_permission.state的状态字段。如果角色不存在role_permission,则状态值必须为0。如何解决这种情况?

收藏集:

/* "role" collection */
{
    "_id" : 1,
    "name" : "Admin"
}


/* "permission" collection */
{
    "_id" : 1,
    "name" : "Add User"
}
{
    "_id" : 2,
    "name" : "Update User"
}
{
    "_id" : 3,
    "name" : "Delete User"
}
{
    "_id" : 4,
    "name" : "List User"
}

/* "role_permission" collection */
{
    "_id" : 1,
    "role_id" : 1,
    "permission_id" : 1,
    "state": 1
}
{
    "_id" : 2,
    "role_id" : 1,
    "permission_id" : 2,
    "state": 1
}
{
    "_id" : 4,
    "role_id" : 1,
    "permission_id" : 4,
    "state": 1
}

预期结果:

/* expecting result */
{
    "role_id": 1,
    "permission_id": 1,
    "permission_name": "Add User",
    "permission_state": 1 // if role_permission is exist for the role: use role_permission.state else: 0
}
{
    "role_id": 1,
    "permission_id": 2,
    "permission_name": "Update User",
    "permission_state": 1 // if role_permission is exist for the role: use role_permission.state else: 0
}
{
    "role_id": 1,
    "permission_id": 3,
    "permission_name": "Delete User",
    "permission_state": 0 // if role_permission is exist for the role: use role_permission.state else: 0
}
{
    "role_id": 1,
    "permission_id": 4,
    "permission_name": "List User",
    "permission_state": 1 // if role_permission is exist for the role: use role_permission.state else: 0
}

1 个答案:

答案 0 :(得分:0)

db.permission.aggregate
([
{ "$lookup" : { "from" : "role_permission", "localField" : "_id", "foreignField" : "permission_id", "as" : "JOIN_1" } }, 
{ "$lookup" : { "from" : "role", "localField" : "JOIN_1.role_id", "foreignField" : "_id", "as" : "JOIN_2" } }, 
{ "$unwind" : { "path" : "$JOIN_1", "preserveNullAndEmptyArrays" : true } }, 
{ "$unwind" : { "path" : "$JOIN_2", "preserveNullAndEmptyArrays" : true } }, 
{ "$project" : 
    {   "_id" : 0, 
        "p_id" : { "$ifNull" : ["$JOIN_1._id", 0] }, 
        "role_id" : { "$ifNull" : ["$JOIN_2._id", 1] }, 
        "permission_id" : "$_id", 
        "permission_name" : "$name", 
        "permission_state" : { "$ifNull" : ["$JOIN_1.state", 0] } 
    } 
}
])