Я пытаюсь реализовать следующий рабочий запрос mongoDb в Spring Data с использованием MongoTemplate
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)