简体   繁体   English

如何在 Spring 数据 MongoDB 中进行此聚合?

[英]How to do this aggregation in Spring Data MongoDB?

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:我不习惯使用 Spring 数据,我正在尝试执行此 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 is a Date type field. day是一个日期类型字段。 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).该查询在 mongo shell 上运行良好,按 _id 过滤,并按年和月分组,以及所有服务的总和(Int 字段)。 But I'm not able to implement it on Spring Data MongoDB.但我无法在 Spring 数据 MongoDB 上实现它。

I've tried with the Aggregation.group() but I'm getting lost because of the nested object in the _id .我已经尝试过Aggregation.group()但由于_id中嵌套的 object ,我迷路了。

as far as I know you must wrap everything in an array like so:据我所知,您必须将所有内容包装在一个数组中,如下所示:

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" }
    }
}])

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM