java - 将计算属性与条件查询一起使用
问题描述
我有一个 mongodb 集合。这些文档有两个字段,称为 rtd(天数,int 值)和时间戳(long 值)。我需要使用 Criteria 查询让所有文档都满足这个条件
如果一个文档是 x
currentTimestamp - x.timestamp 转换为天 < x.rtd
try {
return mongoTemplate.find(query(criteria), PredictiveEntity.class).stream().filter(predictiveEntity ->
predictiveEntity.getRtd() >= TimeUnit.DAYS.convert(Instant.now().toEpochMilli() - predictiveEntity.getTimestamp(), TimeUnit.MILLISECONDS)
).collect(Collectors.toList());
} catch (Exception e) {
return null;
}
解决方案
以下查询可以获得预期的输出:
db.predictiveentry.find({
$expr:{
$lt:[
{
$toInt:{
$divide:[
{
$subtract:[new Date().getTime(), "$timestamp"]
},
86400000
]
}
},
"$rtd"
]
}
})
由于 Criteria 中仍然不支持 $expr,我们需要遵循不同的路线,即直接解析 BSON 查询。
Query query = new BasicQuery("{ $expr:{ $lt:[ { $toInt:{ $divide:[ { $subtract:[new Date().getTime(), '$timestamp'] }, 86400000 ] } }, '$rtd' ] } }");
return mongoTemplate.find(query, PredictiveEntity.class).stream().collect(Collectors.toList());
推荐阅读
- regex - 如何在 Google Data Studio 中使用 REGEXP_EXTRACT 提取第一个 / 和第二个 / 之间的所有字符?
- form-recognizer - 表单识别器在单个模型下组合多个自定义模型的限制是什么
- pine-script - 如何在右侧放置指定的斐波那契标签,并缩短线条以不一直延伸到右侧?
- java - 如何在 NetBeans 8.2 RC 中配置代理设置?
- python - 使用 PyTorch 加载 RoBerta 时如何修复严格错误
- postgresql - MADLib + PostgreSQL 查询计划
- c# - 更改文件系统的 Git 操作不会触发 FileWatcher
- python - 线图颜色取决于列表值
- caching - 为什么非连续加载更快,即使缓存未命中惩罚保证为零?
- android - 让 Android KeyStore 在出厂重置中幸存