MongoTemplate:匹配特定条件的文档的键值总和

par*_*rth 5 java mongodb spring-mongo mongotemplate spring-mongodb

我的以下 mongodb 查询按预期工作

db.importedDataItems.aggregate({
    $match: {
        mobile: "1234567890"
    }
}, {
    $group: {
        _id: 'mobile',
        calls: { $sum: '$calls' }
    }
 })
Run Code Online (Sandbox Code Playgroud)

但即使在参考这些 问题教程之后,其等效的 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);
Run Code Online (Sandbox Code Playgroud)

...返回一个空列表并抛出IndexOutOfBoundsException虽然我的查询在控制台上返回结果!

chr*_*dam 4

您缺少参数的右括号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);
Run Code Online (Sandbox Code Playgroud)