简体   繁体   中英

Mongodb query on date has no results (java)

My mongodb query is not returning any results and I can't spot why.

Here is the relevant contents of my data:

> db.reports.find({},{endDate:1})
{ "_id" : ObjectId("5182882ae4b032c67674c494"), "endDate" : ISODate("2013-05-02T15:37:11.032Z") }
{ "_id" : ObjectId("51828859e4b032c67674c495"), "endDate" : ISODate("2013-05-02T15:37:57.749Z") }

So I have two entries with dates 2013-05-02 15:37:11-57

I want to find all entries with a date less than or equal to that latest date, but I get no results using this query:

db.reports.find({ "endDate" : { "$lte" : { "$date" : "2013-05-02T15:37:11.032Z"}}},{endDate:1})

I am generating the query in java using:

BasicDBObject oldReportSelector = (BasicDBObject) BasicDBObjectBuilder.start()
    .add("endDate", 
        BasicDBObjectBuilder.start().add("$lte",myDate).get())
    .get();

What am I doing wrong here?

Edit to add: myDate is calculated using:

Date endDate = new Date()
Date myDate = new Date(endDate.getTime()-(interval*quantityArchivedReports));

Currently interval = 86400000 and quantityArchivedReports = 4

The reason you are not getting anything in the shell is that you are not using the date format the shell expects. Try changing your query to:

> db.reports.find({ "endDate" : { "$lte" : new Date("2013-05-02T15:37:11.032Z")}})

{ "_id" : ObjectId("5182882ae4b032c67674c494"), "endDate" : ISODate("2013-05-02T15:37:11.032Z") }

You can then use the shell to verify if your code has actually generated a correct date to get back any data or not.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM