我似乎无法在 MongoDB 中使用最基本的日期查询。文档看起来像这样:
{
"_id" : "foobar/201310",
"ap" : "foobar",
"dt" : ISODate("2013-10-01T00:00:00.000Z"),
"tl" : 375439
}
查询如下所示:
{
"dt" : {
"$gte" : {
"$date" : "2013-10-01T00:00:00.000Z"
}
}
}
执行后我得到0 个结果:
db.mycollection.find({
"dt" : { "$gte" : { "$date" : "2013-10-01T00:00:00.000Z"}}
})
知道为什么这不起作用吗?
仅供引用,此查询由 Spring's MongoTemplate 生成所以我无法直接控制最终发送到 MongoDB 的查询。
(附注)
> db.version()
2.4.7
谢谢!
最佳答案
虽然$date
是MongoDB Extended JSON的一部分这就是 mongoexport
默认得到的结果,我认为您不能真正将它用作查询的一部分。
如果尝试使用 $date
进行精确搜索,如下所示:
db.foo.find({dt: {"$date": "2012-01-01T15:00:00.000Z"}})
你会得到错误:
error: { "$err" : "invalid operator: $date", "code" : 10068 }
试试这个:
db.mycollection.find({
"dt" : {"$gte": new Date("2013-10-01T00:00:00.000Z")}
})
或(以下评论由 @user3805045 ):
db.mycollection.find({
"dt" : {"$gte": ISODate("2013-10-01T00:00:00.000Z")}
})
ISODate
可能还需要比较没有时间的日期(由 @MattMolnar 标记)。
根据Data Types in the mongo Shell两者应该是等效的:
The mongo shell provides various methods to return the date, either as a string or as a Date object:
- Date() method which returns the current date as a string.
- new Date() constructor which returns a Date object using the ISODate() wrapper.
- ISODate() constructor which returns a Date object using the ISODate() wrapper.
并使用ISODate
should still return a Date object .
{"$date": "ISO-8601 string"}
。一个可能的示例是 Hadoop 连接器。
关于json - mongodb 中使用 ISODate 进行日期查询似乎不起作用,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/39211555/