在mongodb中使用ISODate进行日期查询似乎不起作用 [英] Date query with ISODate in mongodb doesn't seem to work

查看:2457
本文介绍了在mongodb中使用ISODate进行日期查询似乎不起作用的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我似乎连最基本的日期查询都无法在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
}

查询如下:

{ 
    "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.

(PS)

> db.version()
2.4.7

谢谢!

推荐答案

尽管$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.

这篇关于在mongodb中使用ISODate进行日期查询似乎不起作用的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆