MongoTemplate:符合特定条件的文档的键值求和
MongoTemplate: sum values of keys for documents matching a certain criterion
我的以下 mongodb 查询按预期工作
db.importedDataItems.aggregate({
$match: {
mobile: "1234567890"
}
}, {
$group: {
_id: 'mobile',
calls: { $sum: '$calls' }
}
})
但即使在参考 these questions & tutorial 之后,它的等效 Java 代码...
Aggregation agg = Aggregation.newAggregation(Aggregation.match(Criteria.where("mobile").is("1234567890"),
Aggregation.group("mobile").sum("calls").as("totalCalls"),
Aggregation.project("totalCalls"));
AggregationResults<Doc> results = mongoTemplate.aggregate(agg, "yoCollection",
Doc.class);
Doc doc = results.getMappedResults().get(0);
...returns 一个空列表并抛出 IndexOutOfBoundsException
尽管我的查询 returns 在控制台上得到结果!
您缺少 match()
参数的右括号:
import static org.springframework.data.mongodb.core.aggregation.Aggregation.*;
Aggregation agg = Aggregation.newAggregation(
match(Criteria.where("mobile").is("1234567890")), // <-- missing closing parenthesis
group("mobile").sum("calls").as("totalCalls"),
project("totalCalls")
);
AggregationResults<Doc> results = mongoTemplate.aggregate(agg, "yoCollection", Doc.class);
Doc doc = results.getMappedResults().get(0);
我的以下 mongodb 查询按预期工作
db.importedDataItems.aggregate({
$match: {
mobile: "1234567890"
}
}, {
$group: {
_id: 'mobile',
calls: { $sum: '$calls' }
}
})
但即使在参考 these questions & tutorial 之后,它的等效 Java 代码...
Aggregation agg = Aggregation.newAggregation(Aggregation.match(Criteria.where("mobile").is("1234567890"),
Aggregation.group("mobile").sum("calls").as("totalCalls"),
Aggregation.project("totalCalls"));
AggregationResults<Doc> results = mongoTemplate.aggregate(agg, "yoCollection",
Doc.class);
Doc doc = results.getMappedResults().get(0);
...returns 一个空列表并抛出 IndexOutOfBoundsException
尽管我的查询 returns 在控制台上得到结果!
您缺少 match()
参数的右括号:
import static org.springframework.data.mongodb.core.aggregation.Aggregation.*;
Aggregation agg = Aggregation.newAggregation(
match(Criteria.where("mobile").is("1234567890")), // <-- missing closing parenthesis
group("mobile").sum("calls").as("totalCalls"),
project("totalCalls")
);
AggregationResults<Doc> results = mongoTemplate.aggregate(agg, "yoCollection", Doc.class);
Doc doc = results.getMappedResults().get(0);