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 ?

Adarsh Patel
  • 103
  • 1
  • 6
  • what have you tried so far? And also i think your expected output isnt correct. 5+6+5 = 16 and 8+8 =16 – pvpkiran Feb 14 '18 at 08: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 ? – Adarsh Patel Feb 14 '18 at 08:21
  • how is 5+6+5 = 25 and 8+8 =18 can you please explain this – pvpkiran Feb 14 '18 at 08:26
  • Sry mistake in choosing wrong output. i have shown result of id:1 my mistake @pvpkiran – Adarsh Patel Feb 14 '18 at 08: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 – pvpkiran Feb 14 '18 at 11:49

1 Answers1

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;
}
pvpkiran
  • 25,582
  • 8
  • 87
  • 134
  • 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? – Wrong Jun 07 '19 at 08:40