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

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/19819870/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-09-03 20:00:53  来源:igfitidea点击:

Date query with ISODate in mongodb doesn't seem to work

jsonmongodbbsonisodate

提问by Jason Polites

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:

我似乎无法在 MongoDB 中使用最基本的日期查询。使用看起来像这样的文档:

{
    "_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"
        }
    }
}

I get 0 resultsfrom executing:

我从执行中得到0 个结果

db.mycollection.find({
  "dt" : { "$gte" : { "$date" : "2013-10-01T00:00:00.000Z"}}
})

Any idea why this doesn't work?

知道为什么这不起作用吗?

For reference, this query is being produced by Spring's MongoTemplateso I don't have direct control over the query that is ultimately sent to MongoDB.

作为参考,此查询由Spring 的 MongoTemplate生成,因此我无法直接控制最终发送到 MongoDB 的查询。

(P.S.)

(附注)

> db.version()
2.4.7

Thanks!

谢谢!

回答by zero323

Although $dateis a part of MongoDB Extended JSONand that's what you get as default with mongoexportI don't think you can really use it as a part of the query.

虽然$dateMongoDB Extended JSON的一部分,这就是您默认获得的内容,但mongoexport我认为您不能真正将其用作查询的一部分。

If try exact search with $datelike below:

如果尝试使用$date以下方式进行精确搜索:

db.foo.find({dt: {"$date": "2012-01-01T15:00:00.000Z"}})

you'll get error:

你会得到错误:

error: { "$err" : "invalid operator: $date", "code" : 10068 }

Try this:

尝试这个:

db.mycollection.find({
    "dt" : {"$gte": new Date("2013-10-01T00:00:00.000Z")}
})

or (following comments by @user3805045):

或(遵循@user3805045 的评论):

db.mycollection.find({
    "dt" : {"$gte": ISODate("2013-10-01T00:00:00.000Z")}
})

ISODatemay be also required to compare dates without time (noted by @MattMolnar).

ISODate可能还需要比较没有时间的日期(@MattMolnar指出)。

According to Data Types in the mongo Shellboth should be equivalent:

根据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.

mongo shell 提供了各种方法来返回日期,可以是字符串,也可以是 Date 对象:

  • Date() 方法以字符串形式返回当前日期。
  • new Date() 构造函数,它使用 ISODate() 包装器返回一个 Date 对象。
  • ISODate() 构造函数,它使用 ISODate() 包装器返回一个 Date 对象。

and using ISODateshould still return a Date object.

并且 usingISODate仍然应该返回一个 Date 对象

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

{"$date": "ISO-8601 string"}当需要严格的 JSON 表示时可以使用。一个可能的例子是 Hadoop 连接器。

回答by Steve HHH

From the MongoDB cookbookpage comments:

来自MongoDB 食谱页面的评论:

"dt" : 
{
    "$gte" : ISODate("2014-07-02T00:00:00Z"), 
    "$lt" : ISODate("2014-07-03T00:00:00Z") 
}

This worked for me. In full context, the following command gets every record where the dtdate field has a date on 2013-10-01 (YYYY-MM-DD) Zulu:

这对我有用。在完整上下文中,以下命令获取dt日期字段在 2013-10-01 (YYYY-MM-DD) Zulu 上具有日期的每条记录:

db.mycollection.find({ "dt" : { "$gte" : ISODate("2013-10-01T00:00:00Z"), "$lt" : ISODate("2013-10-02T00:00:00Z") }})

回答by Jabba

Try this:

尝试这个:

{ "dt" : { "$gte" : ISODate("2013-10-01") } }

回答by siddharthrc

I am using robomongo as the mongodb client gui and the below worked for me

我使用 robomongo 作为 mongodb 客户端 gui,以下对我有用

db.collectionName.find({"columnWithDateTime" : {
$lt:new ISODate("2016-02-28T00:00:00.000Z")}})

On the app side I am using nodejs based driver mongodb(v1.4.3),the application uses datepicker in the ui which gives date like YYYY-mm-dd, this is then appended with default time like 00:00:00 and then given to the new Date()constructor and then supplied to the mongodb criteria object,I think the driver converts the date to ISO date and the query then works and gives desired output, however the same new Date()constructor does not work or show same output on robo mongo,for the same criteria,which is weird,since I used robomongo to cross check my criteria objects.

在应用程序方面,我使用基于 nodejs 的驱动程序 mongodb(v1.4.3),该应用程序在 ui 中使用 datepicker,它给出像 YYYY-mm-dd 这样的日期,然后附加默认时间,如 00:00:00 然后给出到new Date()构造函数,然后提供给 mongodb 条件对象,我认为驱动程序将日期转换为 ISO 日期,然后查询工作并提供所需的输出,但是相同的new Date()构造函数不起作用或在 robo mongo 上显示相同的输出,对于相同的标准,这很奇怪,因为我使用 robomongo 来交叉检查我的标准对象。

Whereas the default cli mongoshell works well with both ISODateand new Date()

而默认的 cli mongoshell 适用于两者ISODatenew Date()

回答by 3vangelos

In json strict mode, you'll have to keep the order:

在 json 严格模式下,您必须保持顺序:

{
    "dt": {
        "$gte": {
            "$date": "2013-10-01T00:00:00.000Z"
        }
    }
}

Only thing which worked to define my search queries on mlab.com.

唯一能在 mlab.com 上定义我的搜索查询的东西。

回答by lewma

In the MongoDB shell:

在 MongoDB 外壳中:

db.getCollection('sensorevents').find({from:{$gt: new ISODate('2015-08-30 16:50:24.481Z')}})

In my nodeJS code ( using Mongoose )

在我的 nodeJS 代码中(使用 Mongoose)

    SensorEvent.Model.find( {
        from: { $gt: new Date( SensorEventListener.lastSeenSensorFrom ) }
    } )

I am querying my sensor events collection to return values where the 'from' field is greater than the given date

我正在查询我的传感器事件集合以返回“来自”字段大于给定日期的值

回答by coder

this is my document

这是我的文件

"_id" : ObjectId("590173023c488e9a48e903d6"),
    "updatedAt" : ISODate("2017-04-27T04:26:42.709Z"),
    "createdAt" : ISODate("2017-04-27T04:26:42.709Z"),
    "flightId" : "590170f97cb84116075e2680",

 "_id" : ObjectId("590173023c488e9a48e903d6"),
        "updatedAt" : ISODate("2017-04-28T03:26:42.609Z"),
        "createdAt" : ISODate("2017-04-28T03:26:42.609Z"),
        "flightId" : "590170f97cb84116075e2680",

now i want to find every 27th date document.so i used this....

现在我想找到每个第 27 个日期的文件。所以我用了这个....

 > db.users.find({createdAt:{"$gte":ISODate("2017-04-27T00:00:00Z"),"$lt":ISODate("2017-04-28T00:00:00Z") }}).count()

result:1

this worked for me.

这对我有用。

回答by JulienRioux

This worked for me while searching for value less than or equal than now:

在搜索小于或等于现在的值时,这对我有用:

db.collectionName.find({ "dt": { "$lte" : new Date() + "" } });

回答by Ehsan sarshar

Wrap it with new Date():

用它包裹new Date()

{ "dt" : { "$lt" : new Date("2012-01-01T15:00:00.000Z") } }