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

时间:2015-10-28 11:56:04

标签: java mongodb spring-mongo mongotemplate spring-mongodb

我的以下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);

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

1 个答案:

答案 0 :(得分:3)

您缺少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);