检查条件字段datetime是否大于等于mongodb中使用node js的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?

你应该使用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/

最新更新