简体   繁体   English

如何在 spring 中在 mongo 模板中编写此聚合查询

[英]How to write this Aggregate query in mongo template in spring

I want to write this aggregate query in mongo template using spring.我想使用 spring 在 mongo 模板中编写这个聚合查询。

This is my query:这是我的查询:

db.getCollection('CANdata_fc_distance_report').aggregate(
    {$match: { device_datetime : { $gte :1462041000000, $lte: 1462732200000 }}},
    {"$group" : {_id:{fc :"$fc",vehicle_name:"$vehicle_name",
        device_id : "$device_id"},
    count:{$sum:1}}}
)

This is the result of the above query这是上面查询的结果

/* 1 */
{
    "_id" : {
        "fc" : NumberLong(1),
        "vehicle_name" : "WPD 9020",
        "device_id" : NumberLong(157)
    },
    "count" : 2
}    
/* 2 */
{
    "_id" : {
        "fc" : NumberLong(2),
        "vehicle_name" : "VVD 8966",
        "device_id" : NumberLong(137)
    },
    "count" : 1
}

This is my data in table:这是我在表中的数据:

/* 1 */
{
    "_id" : ObjectId("581829855d08921ee6f0ac39"),
    "_class" : "com.analysis.model.mongo.fc_distance_report",
    "device_id" : NumberLong(137),
    "vehicle_name" : "VVD 8966",
    "distance" : 125.01,
    "fc" : NumberLong(1),
    "device_datetime" : NumberLong(1462041000000)
}

/* 2 */
{
    "_id" : ObjectId("581830335d08921ee6f0ad6b"),
    "_class" : "com.analysis.model.mongo.fc_distance_report",
    "device_id" : NumberLong(137),
    "vehicle_name" : "VVD 8966",
    "distance" : 171.88,
    "fc" : NumberLong(2),
    "device_datetime" : NumberLong(1462127400000)
}

I found example in my google search added match criteria but I have no idea how to write grouping on 3 columns我在我的 google 搜索中发现示例添加了匹配条件,但我不知道如何在 3 列上编写分组

Aggregation agg = newAggregation(match(Criteria.where("device_datetime").exists(true)
                            .andOperator(
    Criteria.where("device_datetime").gte(startDate),
    Criteria.where("device_datetime").lte(endDate))),
    group("hosting").count().as("total"),
    project("total").and("hosting").previousOperation(),
    sort(Sort.Direction.DESC, "total")
    );

Please help me.请帮帮我。 Thank you谢谢

You can try something like this.你可以尝试这样的事情。 Just and the group keys together.只是和组键在一起。

Aggregation agg = newAggregation(match(Criteria.where("device_datetime").exists(true)
        .andOperator(
            Criteria.where("device_datetime").gte(startDate),
            Criteria.where("device_datetime").lte(endDate))),
    group(Fields.fields().and("fc", "$fc").and("vehicle_name", "$vehicle_name").and("device_id", "$device_id"))
    .count().as("count"));

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

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