2016-12-07 52 views
0

我在Java中使用嗎啡與MongoDB中,我想獲得多項紀錄聚集查詢這樣的:如何使用mongoDB中的morphia獲取累加器結果?

AggregationPipeline pipCount = ds.createAggregation(MyTable.class) 
      .match(query1) 
      .match(query2) 
      .unwind("transactions") 
      .match(query3) 
      .group("_id", grouping("_id"), grouping("count", new Accumulator("$sum", 1))); 
Iterator<MyTable> result = pipCount.aggregate(MyTable.class); 

我需要使用分組(「_ ID」),刪除重複的結果,然後算結果,但無法找到任何方式來讀取總和值... 任何想法?

樣本數據:

{ 
    "_id": "00000222", 
    "create_date": ISODate("2015-05-06T07:20:31.000+0000"), 
    "update_date": ISODate("2015-05-06T07:20:31.000+0000"), 
    "payment": 70.0, 
    "fee": 0.0, 
    "type": "RECURRING", 
    "currency": "USD", 
    "status": "OK", 
    "transactions": [{ 
     "_id": "111111223", 
     "amount": 1260.0, 
     "fee_type": "VARIABLE_ADD", 
     "fee_rate": 2.75, 
     "status": "ERROR", 
     "charges": [{ 
      "_id": "2222223344", 
      "amount": 1000.0, 
      "recurring": true, 
      "firstTime": false, 
      "oneTime": true, 
     }, { 
      "_id": "222222222233221", 
      "amount": 70.0, 
      "recurring": true, 
      "firstTime": true, 
      "oneTime": true, 
     }] 
    }], 
    "users": { 
     "_id": "33333333332212", 
     "update_date": ISODate("2015-12-18T08:03:35.000+0000"), 
     "user_id": "[email protected]", 
     "first_name": "dsjfj", 
     "last_name": "skdfjf", 
    } 
} 

結果:1

+1

爲什麼我們用_id分組兩次?請考慮添加示例文檔和預期輸出。 – Veeram

回答

1

你可以嘗試這樣的事情。你不需要額外的分組。第一組將處理重複數據,並計算總數並計算計數並將響應映射到文檔並讀取計數。

import org.bson.Document; 

AggregationPipeline pipCount = datastore.createAggregation(MyTable.class) 
      .match(query1) 
      .match(query2) 
      .unwind("somethingID") 
      .match(query3) 
      .group("_id", grouping("count", new Accumulator("$sum", 1))) 
      .project(Projection.projection("count")); 

    Iterator<Document> result = pipCount.aggregate(Document.class); 

    while (result.hasNext()) { 
     Document document = result.next(); 
     Integer count = document.getInteger("count"); 
    } 
+0

你知道更好的方法來統計AggregationPipeline的所有記錄嗎?原因不明,這種方式不再有效。 – Reza

+0

你看到任何錯誤?你的MyTable類結構是否改變了?我認爲除了在小組階段 – Veeram

+0

中加總行之外,沒有其他辦法可以返回一個ID爲count = 0的列表,而不是隻有一個總數爲count的記錄! – Reza