使用 Spring 数据投影新数组字段
Project New Array Field with Spring Data
作为聚合操作的一部分,我需要展开一个数组。我想知道如何将对象作为项目的一部分放回数组中。这是有效的 MongoDB 聚合操作:
db.users.aggregate([ { "$match" : {...} , { "$unwind" : "$profiles"} ,{$project: {'profiles': ['$profiles']}}...}
更具体地说,我如何使用 Spring 数据 mongoDB ProjectionOperation:
来实现它
{$project: {'profiles': ['$profiles']}}
此功能自 3.2 后添加。
编辑 1:
我浏览了一些帖子和一个答案
:
根据答案,我想出了如下有效的方法:
AggregationOperation project = aggregationOperationContext -> {
Document projection = new Document();
projection.put("profiles", Arrays.<Object> asList("$profiles"));
projection.put("_id","$id");
return new Document("$project", projection);
};
我想知道是否有更好的方法。
非常感谢任何 help/suggestion。谢谢。
很遗憾没有。
您可以将 $project
替换为 project()
并使用 AggregationExpression
来缩短它。
// ...
unwind("profiles"),
project().and(ctx -> new Document("profiles", asList("$profiles"))).as("profiles")
我创建 DATAMONGO-2312 是为了在下一个版本中提供对新数组字段投影的支持。
作为聚合操作的一部分,我需要展开一个数组。我想知道如何将对象作为项目的一部分放回数组中。这是有效的 MongoDB 聚合操作:
db.users.aggregate([ { "$match" : {...} , { "$unwind" : "$profiles"} ,{$project: {'profiles': ['$profiles']}}...}
更具体地说,我如何使用 Spring 数据 mongoDB ProjectionOperation:
来实现它{$project: {'profiles': ['$profiles']}}
此功能自 3.2 后添加。
编辑 1:
我浏览了一些帖子和一个答案
根据答案,我想出了如下有效的方法:
AggregationOperation project = aggregationOperationContext -> {
Document projection = new Document();
projection.put("profiles", Arrays.<Object> asList("$profiles"));
projection.put("_id","$id");
return new Document("$project", projection);
};
我想知道是否有更好的方法。 非常感谢任何 help/suggestion。谢谢。
很遗憾没有。
您可以将 $project
替换为 project()
并使用 AggregationExpression
来缩短它。
// ...
unwind("profiles"),
project().and(ctx -> new Document("profiles", asList("$profiles"))).as("profiles")
我创建 DATAMONGO-2312 是为了在下一个版本中提供对新数组字段投影的支持。