【发布时间】:2019-12-13 08:41:49
【问题描述】:
我想聚合一组符合特定条件的文档,将它们分组并将输出映射到不同的类对象。聚合工作正常,我得到了预期的total,但_id 字段始终为NULL。
我正在使用 spring-data-mongodb 2.1.11 和 MongoDB 3.6。
这是要聚合的类:
@Document
public class LegOrder {
public static class Key {
@Indexed
long itemId;
long transactionId;
...
}
@Id
private Key id;
@Indexed
private long brandId;
private int units;
...
}
这是聚合输出类:
@Document
public class ItemAggregation {
public static class Key {
@Indexed
long itemId;
@Indexed
long brandId;
}
@Id
private Key id;
private long total;
...
}
我的聚合方法:
public ItemAggregation aggregate(long itemId, long brandId) {
MatchOperation matchStage = Aggregation.match(new Criteria().andOperator(
Criteria.where("id.itemId").is(itemId),
Criteria.where("brandId").is(brandId)
));
GroupOperation groupStage = Aggregation.group("id.itemId", "brandId")
.sum("units").as("total")
...
;
Aggregation aggregation = Aggregation.newAggregation(matchStage, groupStage);
return mongoTemplate.aggregate(aggregation, LegOrder.class, ItemAggregation.class).getUniqueMappedResult();
}
在 MongoDB 中执行的查询:
[
{
"$match": {
"$and": [
{ "_id.itemId": 1 },
{ "brandId": 2}
]
}
},
{
"$group": {
"_id": {
"itemId": "$_id.itemId",
"brandId": "$brandId"
},
"total": { "$sum": "$units" }
}
}
]
如果我在 mongo shell 中运行此查询,_id 字段会正确填充。
知道如何实现吗?
谢谢
【问题讨论】:
标签: java spring mongodb aggregation-framework spring-data-mongodb