Mongo 模板聚合 java spring GroupBy

Mongo Template Aggregtion java spring GroupBy

db.billingDomain.aggregate([
  {
    $group: {
      _id: {
        day: { $dayOfMonth: "$createdAt" },
        month: { $month: "$createdAt" },
        year: { $year: "$createdAt" }
      },
      count: {
        $sum: 1
      },
      date: {
        $first: "$createdAt"
      }
    }
  },
  {
    $project: {
      date: {
        $dateToString: {
          format: "%Y-%m-%d",
          date: "$date"
        }
      },
      count: 1,
      _id: 0
    }
  },
  {
    $match: {
      "date": {
        $gte: "2020-06-05"
      }
    }
  }
])

如何使用 mongo 模板、聚合在 spring java 中构建此查询?面临进行此查询的挑战

Spring Mongo不支持所有MongoDB语法,所以我们需要AggregationOperation手动实现(Java > =v1.8):

import static org.springframework.data.mongodb.core.aggregation.Aggregation.*;
import static org.springframework.data.mongodb.core.query.Criteria.*;
import static org.springframework.data.mongodb.core.aggregation.DateOperators.*;


Aggregation agg = newAggregation(
    op -> new Document("$group",
        new Document("_id",
            new Document("day", new Document("$dayOfMonth", "$createdAt"))
                .append( "month", new Document("$month", "$createdAt"))
                .append( "year", new Document("$year", "$createdAt")))
        .append("count", new Document("$sum", 1))
        .append("date", new Document("$first", "$createdAt"))),
    project("count")
        .andExclude("_id")
        .and(dateOf("date").toString("%Y-%m-%d")).as("date"),
    match(where("date").gte("2020-06-05")));

AggregationResults<OutputClass> result = mongoTemplate.aggregate(agg,
    mongoTemplate.getCollectionName(BillingDomain.class), OutputClass.class);

编辑: System.out.println(agg);

{
   "aggregate":"__collection__",
   "pipeline":[
      {
         "$group":{
            "_id":{
               "day":{
                  "$dayOfMonth":"$createdAt"
               },
               "month":{
                  "$month":"$createdAt"
               },
               "year":{
                  "$year":"$createdAt"
               }
            },
            "count":{
               "$sum":1
            },
            "date":{
               "$first":"$createdAt"
            }
         }
      },
      {
         "$project":{
            "count":1,
            "_id":0,
            "date":{
               "$dateToString":{
                  "format":"%Y-%m-%d",
                  "date":"$date"
               }
            }
         }
      },
      {
         "$match":{
            "date":{
               "$gte":"2020-06-05"
            }
         }
      }
   ]
}