2015-10-28 39 views
2

我下面MongoDB的查詢工作,甚至提到thesequestions & tutorial,其等效的Java代碼後,如預期MongoTemplate:匹配一定準則

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

但文件鍵和值...

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雖然我的查詢返回控制檯上的結果!

回答

0

你缺少一個右括號爲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); 
+0

格式化長鏈方法後,它的工作!謝謝,也許錯過右括號是問題,但我想知道爲什麼日食沒有警告我:) – parth