【问题标题】:How to do this aggregation in Spring Data MongoDB?如何在 Spring Data MongoDB 中进行这种聚合?
【发布时间】:2026-01-10 00:45:02
【问题描述】:

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

db.collection.aggregate(
    { $match: { "car._id": "abc1234" } },
    {
        $project: {
            month: { $month: "$day" },
            year: { $year: "$day" },
            services: 1
        }
    },
    {
        $group: {
            _id: { month: "$month", year: "$year" },
            total: { $sum: "$services" }
        }
    }
)

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

我已尝试使用 Aggregation.group(),但由于 _id 中的嵌套对象,我迷路了。

【问题讨论】:

    标签: java spring mongodb spring-data spring-data-mongodb


    【解决方案1】:

    据我所知,您必须像这样将所有内容包装在一个数组中:

    db.collection.aggregate([
    { $match: { "car._id": "abc1234" } },
    {
        $project: {
            month: { $month: "$day" },
            year: { $year: "$day" },
            services: 1
        }
    },
    {
        $group: {
            _id: { month: "$month", year: "$year" },
            total: { $sum: "$services" }
        }
    }])
    

    【讨论】:

      最近更新 更多