Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Spring data mongodb - aggregation framework integration

I started to use MongoDB database in my application and for data access I have chosen Spring Data for MongoDB.

I skimmed API reference and documentation and I can see that there is map-reduce integration but what about aggregation framework? I can see that it supports group by operation, which would indicate that it supports $group operator judging from this: http://docs.mongodb.org/manual/reference/sql-aggregation-comparison/, but what about other operators, are that not supported for now?

I am asking this question because I wanted to know what kind of integration with MongoDB Sping Data provides so I know what to expect, so to speak.

like image 607
Andna Avatar asked Mar 25 '13 20:03

Andna


3 Answers

Spring Data 1.3.0.RC1 is available and it does support the aggregation framework.

For example: The shell aggregation comand:

db.eft_transactions.aggregate(
    {$match:
        {
            service:"EFT",
            source:"MARKUP",
        }
    },
    {$group:
        {
            _id:"$card_acceptor_id",
            tran_count:{$sum:1},
            amount_sum:{$sum:"$amount"}
        }
    }
)

is run like this from java:

    AggregationOperation match = Aggregation.match(Criteria.where("service").is("EFT").and("source").is("MARKUP"));
    AggregationOperation group = Aggregation.group("card_acceptor").and("amount_sum").sum("amount").and("tran_count").count();
    Aggregation aggregation = newAggregation(match, group);
    AggregationResults<StoreSummary> result = this.mongoTemplate.aggregate(aggregation, "eft_transactions", StoreSummary.class);

The documentation is here

NOTE: We recently had to switch to using the BUILD-SNAPSHOT build of version 1.3.0. This change necessitated the change to 2 of the above lines which have changed to:

AggregationOperation group = Aggregation.group("card_acceptor").sum("amount").as("amount_sum").count().as("tran_count");
Aggregation aggregation = Aggregation.newAggregation(match, group);
like image 139
Ron Tuffin Avatar answered Oct 25 '22 15:10

Ron Tuffin


The Spring Data MongoOperations.group() method is mapped to db.collection.group() MongoDB command and not the $group aggregation function. Currently there is no support in Spring Data MongoDB for aggregation framework. Map reduce, as you have mentioned, is supported though

like image 40
Ori Dar Avatar answered Oct 25 '22 15:10

Ori Dar


 Aggregation aggregation = newAggregation(
        match(Criteria.where("salesyear").is(year)),
        group("brand","salesyear").sum("numberOfCars").as("total"),
        sort(Sort.Direction.ASC, previousOperation(), "brand")    
      );
like image 28
Vicky Avatar answered Oct 25 '22 15:10

Vicky