【问题标题】:MongoTemplate: sum values of keys for documents matching a certain criterionMongoTemplate:匹配某个标准的文档的键值总和
【发布时间】:2016-01-28 04:31:24
【问题描述】:

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

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

但即使在引用thesequestions & 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);

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

【问题讨论】:

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


    【解决方案1】:

    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);
    

    【讨论】:

    • 重新格式化长链方法后,它可以工作了!谢谢,也许缺少右括号是问题所在,但我想知道为什么 eclipse 没有警告我:)
    猜你喜欢
    • 2019-06-18
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2014-08-24
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多