mongo模板aggregation java spring groupby

mo49yndu  于 2021-07-26  发布在  Java
关注(0)|答案(1)|浏览(332)
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模板aggregation在springjava中构建这个查询?面临进行此查询的挑战

eulz3vhy

eulz3vhy1#

并非所有mongodb语法都受 Spring Mongo ,所以我们需要实施 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"
}
}
}
]
}

相关问题