Search code examples
mongodbspring-data-mongodb

quarter query in spring-data-mongodb


I want to frame quarter query in spring-data-mongodb, the query which is taken from stackoverflow is :

db.collection.aggregate([
{
$project: {
  date: 1,
  quarter: {
    $cond: [
      { $lte: [{ $month: "$date" }, 3] },
      "first",
      {
        $cond: [
          { $lte: [{ $month: "$date" }, 6] },
          "second",
          {
            $cond: [{ $lte: [{ $month: "$date" }, 9] }, "third", "fourth"],
          },
        ],
      },
    ],
  },
}},{ $group: { _id: { quarter: "$quarter" }, results: { $push: "$date" } } }]);

Please help me in writing the above query in spring-data-mongodb

Regards

Kris


Solution

  • Use $switch.

    CaseOperator first = CaseOperator
                    .when(ComparisonOperators.Lte.valueOf(DateOperators.dateOf("date").month()).lessThanEqualToValue(3))
                    .then("first");
    CaseOperator second = CaseOperator
                    .when(ComparisonOperators.Lte.valueOf(DateOperators.dateOf("date").month()).lessThanEqualToValue(6))
                    .then("second");
    CaseOperator third = CaseOperator
                    .when(ComparisonOperators.Lte.valueOf(DateOperators.dateOf("date").month()).lessThanEqualToValue(9))
                    .then("third");
    CaseOperator fourth = CaseOperator
                    .when(ComparisonOperators.Lte.valueOf(DateOperators.dateOf("date").month()).lessThanEqualToValue(12))
                    .then("fourth");
    
    ProjectionOperation project = Aggregation.project("date").and(ConditionalOperators.switchCases(first, second, third, fourth)).as("quarter");
    GroupOperation group = Aggregation.group("quarter").push("date").as("results");
    Aggregation aggregation = Aggregation.newAggregation(project, group);
    
    AggregationResults<Document> output = mongoTemplate.aggregate(aggregation, "collection", Document.class);
    

    Mongo Query:

    db.collection.aggregate([
      {"$project":{
        "date":1,
        "quarter":{
          "$switch":{
            "branches":[
              {"case":{"$lte":[{"$month":"$date"},3]},"then":"first"},
              {"case":{"$lte":[{"$month":"$date"},6]},"then":"second"},
              {"case":{"$lte":[{"$month":"$date"},9]},"then":"third"},
              {"case":{"$lte":[{"$month":"$date"},12]},"then":"fourth"}]
          }
        }
      }},
      {"$group":{
        "_id":"$quarter","results":{"$push":"$date"}
      }}
    ])