NodeJS MongoDB:查询 ISO 日期 [英] NodeJS MongoDB: Querying ISO Date
问题描述
我有一个以字符串形式存储在 MongoDB 中的 ISO 日期集合,如下所示:
I have a collection of ISO dates stored in MongoDB as strings, like so:
{ "date": "2014-12-12T03:33:33.333Z" },
{ "date": "2014-12-13T03:33:33.333Z" }
在控制台中,我可以完美地使用
In the console, I can query these perfectly using
{ "date": ISODate("2014-12-12T03:44:00.000Z") }
但是,我使用的是 NodeJS 驱动程序,无法使用 ISODate
.我在这里发现了几个与此问题有关的问题,但建议的解决方案似乎都不起作用.例如:
However, I'm using the NodeJS driver, and I cannot use ISODate
. I have found several questions pertaining to this problem on here, but none of the proposed solutions seem to work. For instance:
// These does not find any matches
db.find({ "date": new Date("2014-12-12T03:44:00.000Z") })
db.find({ "date": { '$eq': '2014-12-12T03:44:00.000Z' } })
db.find({ "date": { '$eq': new Date('2014-12-12T03:44:00.000Z') } })
//This throws an error stating $date is not an operator
db.find({ "date": { '$date': '2014-12-12T03:44:00.000Z' } })
为什么这些查询失败?
这是另一个示例,直接来自数据库:
Here's another sample, straight from the database:
{
"_id": "5a7e88f34b5916723589183f",
"date": "2014-12-12T03:42:00.000Z",
"granularity": 180
}
EDIT 2: 此查询产生以下错误 MongoError: $dateFromString requires that 'dateString' be a string, found: date with value 2014-12-12T03:44:00.000Z
EDIT 2: This query produces the following error MongoError: $dateFromString requires that 'dateString' be a string, found: date with value 2014-12-12T03:44:00.000Z
async loadCandle(date, granularity) {
date = date + ''; //Aded to ensure date is a string, but still get the error.
var candle = await this.data.collection('dates').findOne(
{ $expr :
{$eq :
[
{$dateFromString : {dateString : "$date"}},
new Date("2014-12-12T03:33:33.333Z") //Normally would pass in the `date` variable here
]
} });
推荐答案
因为 $date
不是运算符
需要使用$dateFromString
将字符串日期转换为ISODate
进行比较
you need to use $dateFromString
to convert string date to ISODate
for comparison
db.datez.find(
{$expr :
{$eq :
[
{$dateFromString : {dateString : "$date"}},
new Date("2014-12-12T03:33:33.333Z")
]
}
}
)
使用聚合
db.datez.aggregate([
{$match :
{$expr :
{$eq :
[
{$dateFromString : {dateString : "$date"}},
new Date("2014-12-12T03:33:33.333Z")
]
}
}
}
])
收藏
> db.datez.find()
{ "_id" : ObjectId("5a7e795e80aae386f73cf0fe"), "date" : "2014-12-12T03:33:33.333Z" }
{ "_id" : ObjectId("5a7e795e80aae386f73cf0ff"), "date" : "2014-12-13T03:33:33.333Z" }
>
结果
> db.datez.find({$expr : {$eq : [{$dateFromString : {dateString : "$date"}}, new Date("2014-12-12T03:33:33.333Z")]}})
{ "_id" : ObjectId("5a7e795e80aae386f73cf0fe"), "date" : "2014-12-12T03:33:33.333Z" }
这篇关于NodeJS MongoDB:查询 ISO 日期的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!