首页 > 解决方案 > 将计算属性与条件查询一起使用

问题描述

我有一个 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;
        }

标签: javadatabasemongodbcriteria

解决方案


以下查询可以获得预期的输出:

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());

推荐阅读