2017-09-11 6 views
0

Javaを使用してmongodb集約を実行しようとしており、2つのフィールドを個別に合計する方法を見つけることができません。以下は私の文書構造である:Java MongoDB集約 - 複数のフィールドの合計

{ 
    "_id" : ObjectId("59b6b96423b65d0a04de128d"), 
    "itemCount": 25, 
    "defectiveItemCount": 5, 
    "time": ISODate("x") 
}, 
{ 
    "_id" : ObjectId("59b6b96423b65d0a04de128d"), 
    "itemCount": 20, 
    "defectiveItemCount": 7, 
    "time": ISODate("x") 
} 

私が使用して合計しようとしています:

Aggregation pipeline = newAggregation(
     match(Criteria.where("time").gt(time)), 
     group().sum("itemCount").as("total"), 
     group().sum("defectiveItemCount").as("defective"), 
     project("total").and("defective").previousOperation() 
); 

私も試してみました:

Aggregation pipeline = newAggregation(
     match(Criteria.where("time").gt(time)), 
     group().sum("itemCount").as("total").sum("defectiveItemCount").as("defective"), 
     project("total").and("defective").previousOperation() 
); 

私は、この集約を実行すると、欠陥の結果は常にありますヌル。

私は結果たい:

{ 
    "itemCount": 45, 
    "defectiveItemCount": 12 
} 

は、上記のことは可能ですか、私は2件の別々の集計を実行する必要がありますか?

答えて

1

アキュムレータをグループに追加する必要があります。

何か

よう
Aggregation pipeline = newAggregation(
    match(Criteria.where("time").gt(time)), 
    group().sum("itemCount").as("total").sum("defectiveItemCount").as("defective"), 
    project("total","defective") 
); 
関連する問題