4

Sample Document from Collection

{
    "_id" : 2,
    "student" : "Ryan",
    "homework" : [
        5,
        6,
        5
    ],
    "quiz" : [
        8,
        8
    ],
    "extraCredit" : 8
}

Aggregation Query in mongodb

db.scores.aggregate([
     {
        $project : {
            _id:"$_id",
            hSum : { $sum: "$homework" },
            qSum : { $sum: "$quiz"},
        }
     }])

Output Of above aggregation query

{
    "_id" : 2,
    "hSum" : 16,
    "qSum" : 16
}

I want to convert above mongo query in spring-data format. I want to do aggregation with projectionOperations in spring data. how to write with projectionOperation ?

5
  • what have you tried so far? And also i think your expected output isnt correct. 5+6+5 = 16 and 8+8 =16 Commented Feb 14, 2018 at 8:04
  • i have tried this in mongo terminal. and it is giving shown output. query running fine. i just want to convert that query in spring-data format any help plz ? Commented Feb 14, 2018 at 8:21
  • how is 5+6+5 = 25 and 8+8 =18 can you please explain this Commented Feb 14, 2018 at 8:26
  • Sry mistake in choosing wrong output. i have shown result of id:1 my mistake @pvpkiran Commented Feb 14, 2018 at 8:32
  • aggregate operation makes sens if you are doing over multiple documents. But if you are doing in a single document, it is better if you just read the document and do the calculation in your code Commented Feb 14, 2018 at 11:49

1 Answer 1

4

This should work

MatchOperation matchOperation = match(Criteria.where("_id").is(2));

AggregationExpression homeworkExpression = AccumulatorOperators.Sum.sumOf("homework");
AggregationExpression quizExpression = AccumulatorOperators.Sum.sumOf("quiz");
ProjectionOperation projectionOperation = project("someId").and(homeworkExpression).as("hSum")
        .and(quizExpression).as("qSum");

Aggregation aggregation = newAggregation( matchOperation, projectionOperation);
AggregationResults<Result> results = mongoTemplate.aggregate(aggregation, "ScoresColletionName", Result.class);

You can create a class called Result like this to get the values

@Getter
@Setter
class Result {
    private int someId;
    private int hSum;
    private int qSum;
}
Sign up to request clarification or add additional context in comments.

1 Comment

how can i do this if what i have is an array of objects and I want the sum of a field of all of them?

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.