无法聚合多个集合

Unable to aggregate multiple collections

我有 user 集合,其中包含具有 roleId 的角色对象。我还有 roles 集合,其中包含 id.

现在,对于每个角色,我想获取用户列表。

例如:

[
    {
        "name": "Scott",
        "role": {
            "roleId": "123432"
        }
    },
    {
        "name": "John",
        "role": {
            "roleId": "123432"
        }
    },
    {
        "name": "Scott",
        "role": {
            "roleId": "556432"
        }
    }
]

角色数据:

[
    {
        "id": "123432"
        "name": "admin",
        "type": "internal"
    },
    {
        "id": "556432"
        "name": "owner",
        "type": "external"
    },
    {
        "id": "556432"
        "name": "owner",
        "type": "internal"
    } 
]

现在我想获取internal类型的所有角色及其相关用户:

所以,输出应该是,

[
    {
       "role": "123432",
        "users": [
            {
                "name": "Scott",
                "role": {
                    "roleId": "123432"
                }
            },
            {
                "name": "John",
                "role": {
                    "roleId": "123432"
                }
            }
        ],
        { 
            "role": "556432",
            "users": []
         }
    }
]

我正在与 Spring Boot.if 合作,有人可以帮助我了解如何使用 spring 引导 mongo 获得此聚合,这将非常有帮助为了我。非常感谢。

对您的角色集合执行聚合,并首先根据您的条件筛选出角色。由于您想要所有 internal 个角色,因此您的比赛阶段应该是:

{
    $match: {
      "type": "internal"
    }
}

现在是时候为每个角色查找用户了:

{
    $lookup: {
      from: "user",
      as: "users",
      localField: "id",
      foreignField: "role.roleId"
    }
}

我不知道 mongo 查询是如何在 spring 启动时执行的,但这是它在 mongo 上的执行方式,因此您可以将其转换为您的语言特定代码。

这是 mongo 游乐场上的一个工作示例。

https://mongoplayground.net/p/I1FPuX971YZ