如何使用日期操作编写 Spring 数据 MongoDB 查询

How to write a Spring Data MongoDB query using Date manipulation

我想使用 spring 数据存储库 @Query 注释编写一个 mongodb 查询,这是我的要求:

Get all the Vins that were added in the last sixty minutes and they are still active

"keepAlive" 是特定 VIN 处于活动状态的时间(以毫秒为单位)。当一条记录输入数据库时​​,"keepAlive"可以设置为30分钟、60分钟等

示例数据:

{ vin: "ANBCDERGGGHHGUTY", keepAlive: "3600000", dateAdded: "2019-12-16T16:45:29-05:00" }
{ vin: "T5765ERGGGHHGUTX", keepAlive: "1800000", dateAdded: "2019-11-14T13:41:29-03:00" }

这是我的 类:

public class MyEntity {
    private String vin;
    private long keepAlive;
    private Date dateAdded;
}

我试过类似的方法,但似乎不起作用:

@Query(value = "{'keepAlive':{$lte : {$subtract: [?0, 'dateAdded']}}}")
List<MyEntity> findLatestVins(Date currentSystemDate);

知道我该怎么做吗?

样本数据db.cars.find():

{ "vin" : 1, "keepAlive" : 3600000, "dateAdded" : "2019-12-17T15:00:29+01:00" }
{ "vin" : 2, "keepAlive" : 3600000, "dateAdded" : "2019-12-17T13:00:29+01:00" }
{ "vin" : 3, "keepAlive" : 1800000, "dateAdded" : "2019-12-17T15:00:29+01:00" }

请注意字段 keepAlive 的类型是 number

mongodb 控制台上:

db.cars.find({
    $expr: {
        $gte: [
            "$keepAlive", 
            { 
                $subtract: [
                    new Date(), 
                    {$toDate: "$dateAdded"}
                ]
            }
        ]
    }
})

版本 3.2 兼容(使用聚合管道):

db.collection.aggregate( [ { }, ... ] )

> db.cars.aggregate([
    {
        $project: {
            vin: 1, 
            keepAlive:1, 
            dateAdded:1, 
            notExpired: {
                $gte:[
                    "$keepAlive",
                    { 
                        $subtract:[
                            new Date(),
                            { $toDate:"$dateAdded" }
                        ]
                    }
                ]
            }
        }
    },
    {
        $match: { notExpired: true }
    },
    {
        $project: { notExpired: 0 }
    }
])