如何在Spring Data MongoDB中进行这种聚合?

huangapple 未分类评论48阅读模式
英文:

How to do this aggregation in Spring Data MongoDB?

问题

我不习惯使用Spring Data,我正在尝试进行这个MongoDB聚合,但我无法解决项目和分组部分,匹配部分相当容易:

  1. db.collection.aggregate(
  2. { $match: { "car._id": "abc1234" } },
  3. {
  4. $project: {
  5. month: { $month: "$day" },
  6. year: { $year: "$day" },
  7. services: 1
  8. }
  9. },
  10. {
  11. $group: {
  12. _id: { month: "$month", year: "$year" },
  13. total: { $sum: "$services" }
  14. }
  15. }
  16. )

day 是一个日期类型的字段。这个查询在mongo shell上运行得很好,通过_id进行过滤,并按年份和月份进行分组,以所有服务的总和进行汇总(Int字段)。但是我无法在Spring Data MongoDB中实现它。

我尝试过使用Aggregation.group(),但由于_id中的嵌套对象,我感到有些困惑。

英文:

I'm not used to work with Spring Data and I'm trying to do this MongoDB aggregation but I'm not able to solve the project and group part, match part was pretty easy:

  1. db.collection.aggregate(
  2. { $match: { "car._id": "abc1234" } },
  3. {
  4. $project: {
  5. month: { $month: "$day" },
  6. year: { $year: "$day" },
  7. services: 1
  8. }
  9. },
  10. {
  11. $group: {
  12. _id: { month: "$month", year: "$year" },
  13. total: { $sum: "$services" }
  14. }
  15. }
  16. )

day is a Date type field. The query is working fine on the mongo shell, filtering by _id and grouping by year and months with the sum of all services (Int field). But I'm not able to implement it on Spring Data MongoDB.

I've tried with the Aggregation.group() but I'm getting lost because of the nested object in the _id.

答案1

得分: 0

据我所知,您必须将所有内容包装在一个数组中,如下所示:

  1. db.collection.aggregate([
  2. { $match: { "car._id": "abc1234" } },
  3. {
  4. $project: {
  5. month: { $month: "$day" },
  6. year: { $year: "$day" },
  7. services: 1
  8. }
  9. },
  10. {
  11. $group: {
  12. _id: { month: "$month", year: "$year" },
  13. total: { $sum: "$services" }
  14. }
  15. }
  16. ])
英文:

as far as I know you must wrap everything in an array like so:

  1. db.collection.aggregate([
  2. { $match: { "car._id": "abc1234" } },
  3. {
  4. $project: {
  5. month: { $month: "$day" },
  6. year: { $year: "$day" },
  7. services: 1
  8. }
  9. },
  10. {
  11. $group: {
  12. _id: { month: "$month", year: "$year" },
  13. total: { $sum: "$services" }
  14. }
  15. }])

huangapple
  • 本文由 发表于 2020年7月24日 00:39:46
  • 转载请务必保留本文链接:https://java.coder-hub.com/63059116.html
匿名

发表评论

匿名网友

:?: :razz: :sad: :evil: :!: :smile: :oops: :grin: :eek: :shock: :???: :cool: :lol: :mad: :twisted: :roll: :wink: :idea: :arrow: :neutral: :cry: :mrgreen:

确定