mongodb - 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)
解决方案
推荐阅读
- .net - 如何在 .NET 中使用 REST API 创建 Azure 蓝图
- javascript - 最小输入值取决于第二个输入
- python - 如何使用递归生成交替子串
- javascript - 创建退格按钮
- java - Gluon 保存属性文件
- javascript - 在 Gatsby 中始终提供使用浏览器列表的 Polyfill
- django - Nextjs,Gatsby 用于后端使用 Django 的电子商务网站的服务器端渲染?
- java - sudo R CMD javareconf 解决方案不起作用
- python - 错误 - 不可散列的类型:使用多值执行 groupby 时的“列表”
- .net-core - 缺少 startup.cs program.cs .Net Core Razor