在 mongodb 中使用 ISODate 进行日期查询似乎不起作用 [英] Date query with ISODate in mongodb doesn't seem to work
问题描述
我似乎连最基本的日期查询都无法在 MongoDB 中工作.使用看起来像这样的文档:
I don't seem to be able to get even the most basic date query to work in MongoDB. With a document that looks something like this:
{
"_id" : "foobar/201310",
"ap" : "foobar",
"dt" : ISODate("2013-10-01T00:00:00.000Z"),
"tl" : 375439
}
还有一个看起来像这样的查询:
And a query that looks like this:
{
"dt" : {
"$gte" : {
"$date" : "2013-10-01T00:00:00.000Z"
}
}
}
我从执行中得到 0 个结果:
db.mycollection.find({
"dt" : { "$gte" : { "$date" : "2013-10-01T00:00:00.000Z"}}
})
知道为什么这不起作用吗?
Any idea why this doesn't work?
作为参考,这个查询是由 Spring 的 MongoTemplate 生成的,所以我不无法直接控制最终发送到 MongoDB 的查询.
For reference, this query is being produced by Spring's MongoTemplate so I don't have direct control over the query that is ultimately sent to MongoDB.
(附注)
> db.version()
2.4.7
谢谢!
推荐答案
虽然 $date
是 MongoDB Extended JSON 这就是 mongoexport
的默认设置我认为你不能真正将它用作查询.
Although $date
is a part of MongoDB Extended JSON and that's what you get as default with mongoexport
I don't think you can really use it as a part of the query.
如果尝试使用 $date
进行精确搜索,如下所示:
If try exact search with $date
like below:
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):
or (following comments by @user3805045):
db.mycollection.find({
"dt" : {"$gte": ISODate("2013-10-01T00:00:00.000Z")}
})
ISODate
可能还需要比较没有时间的日期(由 @MattMolnar 指出).
ISODate
may be also required to compare dates without time (noted by @MattMolnar).
根据 mongo Shell 中的数据类型,两者应该是等效的:
According to Data Types in the mongo Shell both should be equivalent:
mongo shell 提供了多种方法来返回日期,可以是字符串,也可以是 Date 对象:
The mongo shell provides various methods to return the date, either as a string or as a Date object:
- Date() 方法以字符串形式返回当前日期.
- new Date() 构造函数,它使用 ISODate() 包装器返回一个 Date 对象.
- ISODate() 构造函数,它使用 ISODate() 包装器返回一个 Date 对象.
并使用 ISODate
仍应返回 Date 对象.
{"$date": "ISO-8601 string"}
可以在需要严格的 JSON 表示时使用.一个可能的例子是 Hadoop 连接器.
{"$date": "ISO-8601 string"}
can be used when strict JSON representation is required. One possible example is Hadoop connector.
这篇关于在 mongodb 中使用 ISODate 进行日期查询似乎不起作用的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!