[英]Implement MongoDB aggregation pipeline with $group stage in java spring
我正在尝试使用Spring mongo在java中实现MongoDB查询。
这是本机MongoDB查询:
db.ShieldReport.aggregate([
{$match:{"sellerCode":"e1aaf3"}},
{$project:{bucketName:"$bucketName", brandName: "$brandName", createdTime : "$createdTime", sellerCode : "$sellerCode"}},
{$sort:{"createdTime":-1}},
{$group:
{
_id: { sellerCode: "$sellerCode", bucketName: "$bucketName", brandName: "$brandName"},
itemsSold: { $first: { bucketName: "$bucketName", brandName: "$brandName", createdTime : "$createdTime"} }
}
},
{$sort:{"itemsSold.createdTime":-1}},
{$project : { _id : "$_id.sellerCode", bucketName :"$itemsSold.bucketName", brandName : "$itemsSold.brandName"}}
])
在我的Spring java版本中,我已经做到了这一点:
Aggregation agg = newAggregation(
match(Criteria.where("sellerCode").is(filterRequest.getSellerCode())),
Aggregation.project("bucketName")
.andInclude("brandName")
.andInclude("createdTime")
.andInclude("sellerCode"),
sort(Sort.Direction.DESC, "createdTime"),
group("sellerCode", "brandName", "bucketName")
);
但问题是我无法创建itemSold
字段。 我该如何创建?
您可以在Spring中重构您的管道,如下所示:
Aggregation agg = Aggregation.newAggregation(
Aggregation.match(Criteria.where("sellerCode").is(filterRequest.getSellerCode())),
Aggregation.sort(Sort.Direction.DESC, "createdTime"),
Aggregation.group("sellerCode", "bucketName", "brandName")
.first("bucketName").as("bucketName")
.first("brandName").as("brandName")
.first("createdTime ").as("createdTime "),
Aggregation.sort(Sort.Direction.DESC, "createdTime"),
Aggregation.project("bucketName", "brandName")
.and("sellerCode").previousOperation()
);
正如您所看到的,已经省略了一些管道阶段,因为它们实际上并不是必需的。 例如, $group
步骤之前的$project
管道可以取消,因为$group
管道运算符将应用累加器
在组步骤中,您将中间过滤的文档按三个字段分组,并将其他字段值存储在$first
运算符辅助的新字段中。
通过上一个组操作的createdTime
字段引用对中间结果进行排序。
最后,在第四步中,从上一个组操作中选择“bucketName”和“brandName”字段。 请注意,“sellerCode”再次隐式引用group-id字段。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.