mongo模板aggregation java spring groupby

mo49yndu  于 2021-07-26  发布在  Java
关注(0)|答案(1)|浏览(406)
  1. db.billingDomain.aggregate([
  2. {
  3. $group: {
  4. _id: {
  5. day: { $dayOfMonth: "$createdAt" },
  6. month: { $month: "$createdAt" },
  7. year: { $year: "$createdAt" }
  8. },
  9. count: {
  10. $sum: 1
  11. },
  12. date: {
  13. $first: "$createdAt"
  14. }
  15. }
  16. },
  17. {
  18. $project: {
  19. date: {
  20. $dateToString: {
  21. format: "%Y-%m-%d",
  22. date: "$date"
  23. }
  24. },
  25. count: 1,
  26. _id: 0
  27. }
  28. },
  29. {
  30. $match: {
  31. "date": {
  32. $gte: "2020-06-05"
  33. }
  34. }
  35. }
  36. ])

如何使用mongo模板aggregation在springjava中构建这个查询?面临进行此查询的挑战

eulz3vhy

eulz3vhy1#

并非所有mongodb语法都受 Spring Mongo ,所以我们需要实施 AggregationOperation 手动(java>= v1.8 ):

  1. import static org.springframework.data.mongodb.core.aggregation.Aggregation.*;
  2. import static org.springframework.data.mongodb.core.query.Criteria.*;
  3. import static org.springframework.data.mongodb.core.aggregation.DateOperators.*;
  4. Aggregation agg = newAggregation(
  5. op -> new Document("$group",
  6. new Document("_id",
  7. new Document("day", new Document("$dayOfMonth", "$createdAt"))
  8. .append( "month", new Document("$month", "$createdAt"))
  9. .append( "year", new Document("$year", "$createdAt")))
  10. .append("count", new Document("$sum", 1))
  11. .append("date", new Document("$first", "$createdAt"))),
  12. project("count")
  13. .andExclude("_id")
  14. .and(dateOf("date").toString("%Y-%m-%d")).as("date"),
  15. match(where("date").gte("2020-06-05")));
  16. AggregationResults<OutputClass> result = mongoTemplate.aggregate(agg,
  17. 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"
}
}
}
]
}

展开查看全部

相关问题