首页 > 解决方案 > Spring数据MongoDB获取文档接近给定日期和时间

问题描述

我正在尝试使用 MongoTemplate 在 Spring Data 中实现以下工作 mongoDb 查询

db.events.aggregate([

    { 
        "$match" : { 
            "someId" : "5bf5372d6518b0b6315d7a29"
        }
    }, 
    { 
        "$project" :{ 
            "totalValue" : 1, 
            "diff" : {
                "$abs":{ 
                    "$subtract" : [ "$dateTime" ,  new Date(2018,11,21,9,0,0)]
                }
            }
        }
    }, 
    {
        "$sort":{ 
            "diff":1
        }
    },
    {
        "$limit":1
    }
])

我已经到了这一点

MatchOperation match = Aggregation.match(Criteria.where("someId").is("idValue"));
        ProjectionOperation projection = Aggregation.project().and("dateTime")
                .minus(format.parse(LocalDate.now().toString() + " 09:00:00").getTime()).as("diff")
                .and("totalValue").as("totalValue");
        SortOperation sort = Aggregation.sort(Sort.Direction.ASC, "diff");
        AggregationResults<Document> result = mongoTemplate
                .aggregate(Aggregation.newAggregation(match, projection, sort), Input.class, Document.class);

以下是文件

db.event.insert([
{someId: "5bf5372d6518b0b6315d7a29", dateTime: new Date(2018,11,21,9,00,11), totalValue: .15},
{someId: "5bf5372d6518b0b6315d7a29", dateTime: new Date(2018,11,21,9,00,01), totalValue: .05},
{someId: "5bf5372d6518b0b6315d7a29", dateTime: new Date(2018,11,21,9,01,11), totalValue: .25},
{someId: "5bf5372d6518b0b6315d7a29", dateTime: new Date(2018,11,21,9,01,51), totalValue: .45},
{someId: "5bf5372d6518b0b6315d7a29", dateTime: new Date(2018,11,21,8,59,02), totalValue: .04},
{someId: "5bf5372d6518b0b6315d7a29", dateTime: new Date(2018,11,21,8,55,11), totalValue: .95},
{someId: "5bf5372d6518b0b6315d7a28", dateTime: new Date(2018,11,21,9,01,51), totalValue: .051},
{someId: "5bf5372d6518b0b6315d7a28", dateTime: new Date(2018,11,21,8,59,02), totalValue: .041},
{someId: "5bf5372d6518b0b6315d7a28", dateTime: new Date(2018,11,21,8,55,11), totalValue: .053},
{someId: "5bf5372d6518b0b6315d7a29", dateTime: new Date(2018,11,22,8,59,02), totalValue: .974},
{someId: "5bf5372d6518b0b6315d7a29", dateTime: new Date(2018,11,22,8,55,11), totalValue: .9},
{someId: "5bf5372d6518b0b6315d7a28", dateTime: new Date(2018,11,22,9,01,51), totalValue: .151},
{someId: "5bf5372d6518b0b6315d7a28", dateTime: new Date(2018,11,22,8,59,02), totalValue: .241}])

预期输出为:0.05(因为它接近日期时间 21-11-2018 09:00:00)

标签: mongodbspring-dataspring-data-mongodbmongotemplate

解决方案


推荐阅读