【问题标题】:MongoTemplate aggregate projection, getting an exception when map array propertiesMongoTemplate聚合投影,映射数组属性时出现异常
【发布时间】:2020-06-17 15:11:53
【问题描述】:

我有两个对象和两个投影对象,如下所示,

主要对象

public class MainItem {
    private String name;
    private List<subItem> subItems;
}


public class subItem {
    private String id;
    private String groupId;
    private String displayName;
    private Status status;
}

投影对象

public class MainItemLight {
    private String name;
    private List<subItemLight> subItemList;
}


public class subItemLight {
    private String id;
    private String name;
}

我正在尝试将 Main 对象映射到投影对象并返回 MainItemLight 对象列表。下面是我的代码,

mongoTemplate.aggregate(
        newAggregation(project("name")
        .and("subItems").as("subItemList")
        .and("subItems.displayName").as("subItemList.name")
    ),
"MyCollection", MainItemLight.class).getMappedResults();

当我尝试将 subItems.displayName 映射到 subItemList.name 时,出现以下异常,

Command failed with error 40176 (Location40176): 'Invalid $project 
:: caused by :: specification contains two conflicting paths. 
Cannot specify both 'subItemList.name' and 'subItemList'

知道如何解决这个问题吗?

【问题讨论】:

  • 删除.and("subItems.displayName").as("subItemList.name")并定义新的$project
  • 喜欢这个?仍然不起作用:/ mongoTemplate.aggregate( newAggregation(project("name") .and("subItems").as("subItemList"), project().and("subItems.displayName").as("subItemList.name") ), "MyCollection", MainItemLight.class).getMappedResults();

标签: mongodb mongodb-query aggregation-framework mongotemplate


【解决方案1】:

你需要这样做:

db.collection.aggregate([
  {
    $project: {
      name: 1,
      subItemList: {
        $map: {
          input: "$subItems",
          as: "item",
          in: {
            id: "$$item.id",
            name: "$$item.displayName"
          }
        }
      }
    }
  }
])

MongoPlayground

蒙古模板

Aggregation agg = newAggregation(project("name").and(
    VariableOperators.Map.itemsOf("subItems").as("item").andApply(
    doc -> new Document()
        .append("id", "$$item.id")
        .append("name", "$$this.displayName")
    )
).as("subItemList"));

注意:$map 的实现在 Spring Mongo 中并不友好,所以我们需要手动实现。

来源:SpringData mongoDB API for Aggregation $map

【讨论】:

  • 谢谢。 MongoTemplate 中 $map 的等效属性是什么?
  • 非常感谢。我不知道这个地图功能:)
猜你喜欢
  • 2019-06-28
  • 1970-01-01
  • 1970-01-01
  • 2013-08-03
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2021-11-23
  • 1970-01-01
相关资源
最近更新 更多