0

I want to extract year, quarter and month from date using spring-data-mongodb and referred to this link Mongodb query specific month|year not date , can someone help me in writing the same query in spring-data-mongodb. Below is the code snippet for extracting year from myDate, with spring-data-mongodb, but it does NOT work.

     Criteria c= null;
     Aggregation agg2 = null;

     c = Criteria.where("year(myDate)").gte(2000).
             andOperator(Criteria.where("year(myDate)").lte(2017);
           agg2 = newAggregation(
                match( c),
              project("retailerName","unitsSold","year" )

                         .andExpression("year(myDate)").as("year"),
                 group(fields().and("retailerName").and("year"))
                 .sum("unitsSold").as("netSales")
                    ,



                  sort(Sort.Direction.ASC, "year")
                 );
               System.out.println("testing : : : " + agg2);
              AggregationResults<ResultTemplate> groupResults = mongoTemplate.aggregate(agg2,ResultTemplate.class,
             ResultTemplate.class);
              System.out.println(groupResults.getMappedResults());
Community
  • 1
  • 1
chiku
  • 485
  • 2
  • 8
  • 23
  • 1
    Actually the question you are linking to has a different purpose, and that is to query for a "month" regardless of the "year" that it falls in. So "select all data for september" is the basic phrase here. What you are asking is "select between these years", which is better expressed with "range operators" `$gte` and `$lt` and actual dates i.e "2000-01-01" and "2018-01-01". Spring has the `.gte()` and `.lt()` helpers to `Criteria` in order to construct such a query. No need for aggregation projection, and much faster. – Blakes Seven Feb 11 '16 at 04:17
  • 2
    Possible duplicate of [Spring Data MongoDB Date Between](http://stackoverflow.com/questions/10311061/spring-data-mongodb-date-between) – Blakes Seven Feb 11 '16 at 04:24
  • Possible duplicate of [Retrieve only the queried element in an object array in MongoDB collection](http://stackoverflow.com/questions/3985214/retrieve-only-the-queried-element-in-an-object-array-in-mongodb-collection) – chridam Feb 11 '16 at 05:29
  • thank you, I implemented the similar concept mentioned in this link http://stackoverflow.com/questions/10311061/spring-data-mongodb-date-between. Well do we not have something like extract function in spring-data-mongodb? It would be easier sometimes. – chiku Feb 11 '16 at 13:31

0 Answers0