首页 > 解决方案 > 查找比较 Mongo 上的两个 DateTime 字段

问题描述

我正在尝试比较同一文档的两个字段,但我需要在其中一个字段上添加几秒钟。

我的查询是:

db.getCollection('period').find({
    $where: function() {
        return this.dt_stop <= this.dt_start.getTime() + 60000 
    } 
})

但我得到下一个错误:

Error: error: {
    "ok" : 0,
    "errmsg" : "TypeError: this.dt_last_start is undefined :\n@:1:15\n",
    "code" : 139,
    "codeName" : "JSInterpreterFailure"
}

我不会在字段中添加第二个。任何想法?

---SOLVE-- 问题是一些文件的this.dt_stop 不存在。最终代码:

db.getCollection('period').find(
{
    "$and" : [ 
        {"dt_stop" : {"$exists" : true}},
        {"dt_start" : {"$exists" : true}}, 
        { $where: function() {return this.dt_end.getTime() <= this.dt_begin.getTime()+60000} 
        } 
    ]
}) 

标签: mongodb

解决方案


Ifdt_stop是一个 ISODate,并且您将它与时间戳 (this.dt_start.getTime() + 60000) 进行比较。

尝试这个

db.getCollection('period').find({
    $where: function() {
        return this.dt_stop.getTime() <= this.dt_start.getTime() + 60000 
    } 
})

推荐阅读