MongoTemplate聚合投影,映射数组属性时出现异常
MongoTemplate aggregate projection, getting an exception when map array properties
我有两个对象和两个投影对象,如下所示,
主要对象
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 对象映射到投影对象和 return 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'
知道如何解决这个问题吗?
你需要这样做:
db.collection.aggregate([
{
$project: {
name: 1,
subItemList: {
$map: {
input: "$subItems",
as: "item",
in: {
id: "$$item.id",
name: "$$item.displayName"
}
}
}
}
}
])
Mongo模板
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
实现在SpringMongo中不友好,需要手动实现。
来源:
我有两个对象和两个投影对象,如下所示,
主要对象
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 对象映射到投影对象和 return 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'
知道如何解决这个问题吗?
你需要这样做:
db.collection.aggregate([
{
$project: {
name: 1,
subItemList: {
$map: {
input: "$subItems",
as: "item",
in: {
id: "$$item.id",
name: "$$item.displayName"
}
}
}
}
}
])
Mongo模板
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
实现在SpringMongo中不友好,需要手动实现。
来源: