且构网

分享程序员开发的那些事...
且构网 - 分享程序员编程开发的那些事

在mongodb中使用ISODate进行日期查询似乎不起作用

更新时间:2021-12-23 21:58:43

尽管$date

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 ):

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中的数据类型,两者应等效:

mongo shell提供了多种返回日期的方法,可以是字符串形式还是Date对象:

The mongo shell provides various methods to return the date, either as a string or as a Date object:

  • Date()方法,以字符串形式返回当前日期.
  • 新的Date()构造函数,该构造函数使用ISODate()包装器返回Date对象.
  • ISODate()构造函数,该构造函数使用ISODate()包装器返回Date对象.
  • 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 仍应返回Date对象.

{"$date": "ISO-8601 string"}.一个可能的例子是Hadoop连接器.

{"$date": "ISO-8601 string"} can be used when strict JSON representation is required. One possible example is Hadoop connector.