【问题标题】:MongoDB $expr expressionMongoDB $expr 表达式
【发布时间】:2020-03-04 20:22:50
【问题描述】:

我有一个集合,我想通过比较 2 个字段和其中一个字段的修改来过滤。 我现在使用 $where 作为这个过滤器(字段是 lastTime 和 Threshold),$where 过滤器看起来像这样

this.lastTime < new Date(ISODate().getTime() - 1000 * 60 * this.Threshold)

我想把$where的用法改成$expr, 我尝试了类似的方法,但它不起作用(如果将 $Threshold 更改为硬编码数字它正在工作)这甚至可能吗?

db.getCollection("test").find({ "$expr" : { "$lt" : ["$lastTime", new Date(ISODate().getTime() - 1000 * 60 * NumberInt("$Threshold"))] } })

我想将 $where 更改为 $expr,这样我就不会使用 javascript 引擎了有什么方法可以实现它(Mongo 4.2)我也试图避免聚合?

谢谢

【问题讨论】:

    标签: mongodb


    【解决方案1】:

    当使用日期和时间时,我推荐moment.js

    这个应该可以的:

    db.getCollection("test").find(
       { "lastTime": { $lt: moment().subtract(this.Threshold, "minutes").toDate() } }
    )
    

    【讨论】:

    • 您必须下载并安装该库。然后你可以加载它,例如load('/home/moment-with-locales.js')
    猜你喜欢
    • 2012-10-06
    • 2022-01-24
    • 1970-01-01
    • 2020-06-14
    • 2020-02-24
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多