Karthik
Karthik

Reputation: 477

Java MongoDB aggregation - sum of multiple fields

I am trying to perform a mongodb aggregation using Java and unable to figure out how to sum 2 fields individually. Below is my document structure:

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

I am trying to sum using:

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

I also tried:

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

When I run this aggregation, the result of defective is always NULL.

I want the result as:

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

Is the above possible or should I perform 2 separate aggregations?

Upvotes: 0

Views: 4389

Answers (1)

s7vr
s7vr

Reputation: 75914

You have to append the accumulators in group.

Something like

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

Upvotes: 3

Related Questions