MongoDB How to Query with the $date operator?

心已入冬 提交于 2019-12-07 22:07:05

问题


Edit - Context: I'm using the Talend ETL tool and using ISODate or Date or new Date in the query like the following fail with an error, so I need a work around:

{'dt' : ISODate('2014-01-01') }
{'dt' : Date('2014-01-01') }
{'dt' : new Date('2014-01-01') }

I cannot do so without the following error:

at com.mongodb.util.JSONParser.read(JSON.java:272)
at com.mongodb.util.JSONParser.parse(JSON.java:161)
at com.mongodb.util.JSONParser.parseObject(JSON.java:231)
at com.mongodb.util.JSONParser.parse(JSON.java:195)
at com.mongodb.util.JSONParser.parse(JSON.java:145)
at com.mongodb.util.JSON.parse(JSON.java:81)
at com.mongodb.util.JSON.parse(JSON.java:66)

presumably because the ETL tool calls:

com.mongodb.DBObject myQuery_tMongoDBInput_1 = (com.mongodb.DBObject) com.mongodb.util.JSON
                    .parse("{'dt': new Date('2000-01-01T08:00:00Z')}");

Given that I cannot use the new Date() in the query for the com.mongodb.util.JSON.parse() method, is there a work around?


I'm using MongoDB v2.6.3 and cannot get the $date operator to work.

db.testdate.insert( {dt:ISODate('2014-01-01')} )
db.testdate.find()

db.testdate.find( {dt : {$date : '2014-01-01T00:00:00Z'}} )

error: { "$err" : "Can't canonicalize query: BadValue unknown top level operator: $date", "code" : 17287 }

db.testdate.find(  {dt : {$gte : {$date : '2000-01-01T00:00:00Z'}}} )

I've seen other examples where the use of the $date operator worked, but cannot get it to do so on my machine.

Does anyone know why?


回答1:


$date is prepared for tools mongoimport, mongoexport, etc. Mongo shell can't recognize it, you should use Date() or ISODate() instead.




回答2:


Based on what is written in documentation, { "$date": "<date>" } is used in a strict mode and in mongoshell you need to use new Date ( <date> )

Take a look how you should query by dates (basically using $gte, $gt, $lte, $lt).

Here are some relevant answers: one and two.




回答3:


When using the $date operator you should pass it Long value indicating the "Epoch Unix Time Stamp"

like: {"time": {"$gte": {"$date": 1570654800000}}}

Note that only mongodump and mongoexport can interpret $date, this won't work from mongo shell



来源:https://stackoverflow.com/questions/26227705/mongodb-how-to-query-with-the-date-operator

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!