首页
学习
活动
专区
圈层
工具
发布
社区首页 >问答首页 >spring-data-mongodb中的季度查询

spring-data-mongodb中的季度查询
EN

Stack Overflow用户
提问于 2021-06-18 14:43:50
回答 1查看 59关注 0票数 1

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

代码语言:javascript
复制
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中编写上述查询

问候

克里斯

EN

回答 1

Stack Overflow用户

回答已采纳

发布于 2021-06-22 15:37:58

使用$switch

代码语言:javascript
复制
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查询:

代码语言:javascript
复制
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"}
  }}
])
票数 1
EN
页面原文内容由Stack Overflow提供。腾讯云小微IT领域专用引擎提供翻译支持
原文链接:

https://stackoverflow.com/questions/68030514

复制
相关文章

相似问题

领券
问题归档专栏文章快讯文章归档关键词归档开发者手册归档开发者手册 Section 归档