0

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?

1 Answer 1

3

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")
 );
Sign up to request clarification or add additional context in comments.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.