spring data mongodb - 日期聚合

时间:2018-02-04 16:28:51

标签: java spring mongodb spring-data aggregate

以下代码未提供预期结果,我已尝试使用多个文档,这些文档的结构如下。

_id: 5a7714d44c75220958e6aa01
imei:355227045347655
point: [3.143453333333333,80.10954]
heading: 0
speed:0
timestamp: 2018-02-04 19:42:36.000
point_distance: 525.25

现在我需要计算每个记录匹配的point_distance与给定imei和时间段的总和。我已尝试使用以下代码实现此目的,但即使存在所需数据也不会返回任何内容。

public Object findDistance(long imei, Date from, Date to) {
    List aggregationOps = new ArrayList<>();
    //operations
    aggregationOps.add(match(Criteria.where("imei").is(imei)));
    aggregationOps.add(match(Criteria.where("timestamp").gte(from)));
    aggregationOps.add(match(Criteria.where("timestamp").lte(to)));
    aggregationOps.add(group("imei").sum("point_distance").as("distance"));
    aggregationOps.add(project("imei").and("distance").previousOperation());

    AggregationOptions agOps = new AggregationOptions.Builder().allowDiskUse(true).cursor(new BasicDBObject()).build();

    return (DistanceInfo) getMongoTemplate()
            .aggregate(newAggregation(aggregationOps).withOptions(agOps), Location.class, DistanceInfo.class)
            .getUniqueMappedResult();
}

Date&gt; fromto的格式为yyyy-MM-dd hh:mm:ss

DistanceInfo上课

public class DistanceInfo {
    long imei;
    double distance;
}

我对这个mongodb的东西不熟悉,不知道我做错了什么,我怎么能纠正这个?非常感谢任何帮助。

1 个答案:

答案 0 :(得分:1)

试试这个。这应该工作

MatchOperation matchOperation = match(Criteria.where("imei").is(imei) 
     .and("timestamp").gte(from.getTime()).lte(to.getTime()));

GroupOperation groupOperation = group("imei").sum("point_distance").as("distance");
ProjectionOperation projectionOperation = project().andExpression("imei").as("imei")
    .andExpression("distance").as("distance");

Aggregation aggregation = newAggregation(matchOperation, groupOperation, projectionOperation);
AggregationResults<DistanceInfo> results = mongoTemplate.aggregate(aggregation, "location", DistanceInfo.class);

return  results.getMappedResults();