首页 > 解决方案 > 使用节点js检查mongo db中的条件字段datetime是否大于或等于currentdatetime

问题描述

我是 mongodb 的新手。我有一个名为conEnd“2020-01-18T16:26:00.000+00:00”的日期字段。我需要检查一个条件,当前日期时间大于或等于日期时间conEnd,取消订阅套接字。

这是我的代码。

    const today = new Date();
    today.setDate(today.getDate());
    const date = (today.getDate() < 10) ? '0' + today.getDate() : today.getDate();
    const month = (today.getMonth() < 10) ? '0' + (today.getMonth() + 1) : today.getMonth() + 1;
    const currentDate = today.getFullYear() + '-' + month + '-' + date;
    const hours = today.getHours();
    const minutes = today.getMinutes();
    const currentdatetime:any= '2021-01-18T16:26:00.000+00:00'//for testing I hard code the time. Otherwise I used currentDate+'T'+hours+':'+minutes+':00.000+00:00';

我在 mongodb 中有一个与当前时间匹配的字段。但是每当我使用下面的代码时,我都会得到空数组 []。

    this.stockcontests.find({conEnd:currentdatetime},{conEnd:1}, function (err, result) {
        if (err){
            console.log(err)
        }else{
            console.log(result)
        }
    });    

没有条件{conEnd : currentdatetime},上面的查询conEnd以这种格式给我:

 conEnd: 2020-01-18T16:26:00.000Z

我也尝试检查此条件但失败了{conEnd : {$gte : currentdatetime} }
如何正确执行条件,在哪里conEnd >= currentdatetime

标签: node.jsmongodb

解决方案


您应该使用 ISODate 来比较 MongoDB 中的日期:

"$gte" : new Date("2021-01-10T10:03:46Z")

ISODate 有效,因为这是您在数据库中的日期格式。

例子

db.getCollection('yourCollection').find({'sampleField': {$gte: new Date('2021-01-10T10:03:46.000Z')}})

您可以在此处查看更多详细信息:

https://docs.mongodb.com/manual/core/shell-types/


推荐阅读