1

I am new to mongodb and spring data, and experimenting with mongodb, is it possible to have pivot operation as mentioned pivot in mongodb using spring data. I have data of this form:

 Name| SumPrice| type|year 
 A|    50.0|     Retail|2015
 B|    467.0|    Online|2015
 A|    1456.0|   Direct|2015
 B|    1149.53|  Direct|2015
 C|     273.20|  Online|2014
 C|     110.0|   Direct|2014

For this I created a java class :

    class SampleReport{

     private String name;
     private Double sumUnitPrice;
     private String type;
     private Integer year;
      } 

I want to pivot w.r.t. type and want the data of the form :

  Name |Retail| Online | Direct| year
  A|     50.0 |  0.0|    1456.0 |    2015
  B|     0.0|    467.0|  1149.53|  2015
  C|     0.0|    273.20| 110.0|     2014

The example you mentioned in the spring data web site is not clear for me or too complex to my understanding, Please lemme know how to do the same for the above example with spring-data. Any answers

Regards

Kris

Community
  • 1
  • 1
chiku
  • 485
  • 2
  • 8
  • 23
  • Any updates please. The example given in spring-data-mongodb site, does not solves the problem. Please help. – chiku Oct 07 '15 at 13:21
  • The link https://dzone.com/articles/aggregation-framework-example, says that its pivot possible with mongodb using addToSet() method in group() method in spring-data-mongodb, I am new to mongodb and spring-data, can someone help me in getting the solution. Kris – chiku Oct 08 '15 at 16:11

1 Answers1

1

As you linked, the answer is already there.

Using spring you will do smth like:

 class ZipInfo {
    String id;
    String city;
    String state;
    @Field("pop") int population;
    @Field("loc") double[] location;
 }

 class City {
   String name;
   int population;
 }

class ZipInfoStats {
    String id;
    String state;
    City biggestCity;
    City smallestCity;
 }

TypedAggregation<ZipInfo> aggregation = newAggregation(ZipInfo.class,
    group("state", "city")
        .sum("population").as("pop"),
    sort(ASC, "pop", "state", "city"),
    group("state")
       .last("city").as("biggestCity")
       .last("pop").as("biggestPop")
       .first("city").as("smallestCity")
       .first("pop").as("smallestPop"),
    project()
       .and("state").previousOperation()
       .and("biggestCity")
       .nested(bind("name", "biggestCity").and("population", "biggestPop"))
       .and("smallestCity")
       .nested(bind("name", "smallestCity").and("population",  "smallestPop")),
    sort(ASC, "state")
 );

Remember that the output of the aggregation will bind in ZipInfo.class.

The reference link to spring mongodb API and documentation.

Alvaro Silvino
  • 9,441
  • 12
  • 52
  • 80