首页 > 解决方案 > mongodb find 的 lt 操作符能否将文档字段作为参数

问题描述

我有一个看起来像这样的文件

{
   "_id":ObjectId("5bcef414b4305f4054571305"),
   "timestamp":   ISODate("2018-10-23T10:12:36.755   Z"),
   "config" : {
       "expiry_duration" : NumberLong(10000)
    }
}

我需要查找过期的文件,即其$datediff(time.Now(), $timestamp)>config.expiry_duration

我不清楚我是否需​​要使用聚合,或者我是否可以使用 find 本身来实现这一点

标签: mongodb

解决方案


您可以使用.find()方法来执行此操作,但您需要$expr运算符(在 MongoDB 3.6 中可用):

db.collection.find({
    $expr: {
        $gt: [ { $subtract: [ ISODate("2018-10-23T16:39:06.266Z"), "$timestamp" ] }, "$config.expiry_duration" ]
    }
})

要获取当前日期,您可以输入new Date()Mongo shell

如果您需要 MongoDB < 3.6 的解决方案,您可以使用.aggregate()$ redact管道阶段:

db.col.aggregate({
    $redact: {
        $cond: {
            if: {  $gt: [ { $subtract: [ ISODate("2018-10-23T16:39:06.266Z"), "$timestamp" ] }, "$config.expiry_duration" ] },
            then: "$$KEEP",
            else: "$$DESCEND"
        }
    }
})

推荐阅读