【问题标题】:Unable to aggregate multiple collections无法聚合多个集合
【发布时间】:2021-09-13 17:53:24
【问题描述】:

我有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 进行此操作。如果有人可以帮助我了解如何使用 Spring Boot mongo 进行此聚合,那对我来说非常有帮助。非常感谢。

【问题讨论】:

    标签: mongodb spring-boot spring-data-mongodb


    【解决方案1】:

    在您的角色集合上执行聚合,并首先根据您的条件过滤掉角色。既然你想要所有internal 角色,你的匹配阶段应该是:

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

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

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

    我不知道在 Spring Boot 上如何执行 mongo 查询,但这是在 mongo 上完成的,因此您可以将其转换为您的语言特定代码。

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

    https://mongoplayground.net/p/I1FPuX971YZ

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 2015-11-26
      • 2019-04-24
      • 2020-02-16
      • 2021-08-17
      • 2018-03-06
      • 2023-03-31
      • 2018-09-10
      相关资源
      最近更新 更多