spring-data-mongodb 中的季度查询

quarter query in spring-data-mongodb

我想在 spring-data-mongodb 中构建季度查询,从 Whosebug 获取的查询是:

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" } } }]);

请帮我在spring-data-mongodb

中写下上面的查询

此致

克里斯

使用$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 查询:

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"}
  }}
])