如何在Spring Data MongoDb聚合中将ConditionalOperator与VariableOperator结合使用

时间:2018-09-21 09:51:01

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

我被迫使用聚合框架和 Spring Data MongoDb 项目操作。

我想做的是通过项目操作来创建对象数组。

考虑此中间聚合结果:

{
  "processes": [
    {
      "id": "101a",
      "ownership": {
        "master": {
          "id": "201a",
          "username": "carl93"
        },
        "assignees": [
          {
            "id": "201a",
            "username": "carl93"
          },
          {
            "id": "202a",
            "username": "susan"
          }
        ]
      }
    },
    {
      "id": "101b",
      "ownership": {
        "master": null,
        "assignees": [
          {
            "id": "201a",
            "username": "carl93"
          },
          {
            "id": "202a",
            "username": "susan"
          }
        ]
      }
    }
  ]
}

我想获得的是这样的:

{
  "responsibleUsers": [
    {
      "id": "201a",
      "username": "carl93",
      "processId": "101a"
    },
    {
      "id": "201a",
      "username": "carl93",
      "processId": "101b"
    },
    {
      "id": "202a",
      "username": "susan",
      "processId": "101b"
    }
  ]
}

从本质上讲,对于每个过程,如果所有权具有主用户,我应该从 master 对象中检索用户名和用户ID,否则我应该从< strong> assignee 数组。

现在我只能处理master不为null的情况, 而我正在使用这样的东西:

ProjectionOperation po = Aggregation.project().and(VariableOperators.mapItemsOf("order.processes").as("rt")
            .andApply(
                    aggregationOperationContext -> {
                        Document document = new Document();
                        document.append("id", "$$rt.master.id");
                        document.append("username", "$$rt.master.username");
                        document.append("processId", "$$rt.id");

                        return document;
                    }
            )).as("responsibleUsers");

对“其他”操作有何建议? 也许我应该使用嵌套的VariableOperations和ConditionalOperations,但我不知道怎么做。

0 个答案:

没有答案