简体   繁体   中英

Query Date on Mongo not working

I try to get a log with a date field on MongoDb called "fecha".

After the execution of my code in Java, I get the next query:

{ "fecha" : { "$gt" : { "$date" : "2015-02-03T01:00:00.000Z"} , "$lt" : { "$date" : "2015-11-22T01:00:00.000Z"}}}

But I don't get any result. These are some samples of the data:

{ "fecha" : ISODate("2015-11-17T07:47:39.709Z") }
{ "fecha" : ISODate("2015-11-17T07:47:42.760Z") }
{ "fecha" : ISODate("2015-11-17T07:47:45.069Z") }
{ "fecha" : ISODate("2015-11-17T07:47:46.874Z") }
{ "fecha" : ISODate("2015-11-17T07:47:47.831Z") }
{ "fecha" : ISODate("2015-11-17T07:47:49.838Z") }
{ "fecha" : ISODate("2015-11-17T07:47:50.867Z") }
{ "fecha" : ISODate("2015-11-17T07:47:53.534Z") }
{ "fecha" : ISODate("2015-11-17T07:47:55.348Z") }
{ "fecha" : ISODate("2015-11-17T07:47:59.271Z") }
{ "fecha" : ISODate("2015-11-17T07:48:06.782Z") }

My Java code is the next:

Date dateI = Date.from(Instant.ofEpochMilli(0));
Date dateF = Date.from(Instant.now());

if(!fechaInicial.isEmpty()){
    dateI = Date.from(LocalDateTime.parse(fechaInicial).toInstant(ZoneOffset.UTC));
}    

if(!fechaFinal.isEmpty()){
    dateF = Date.from(LocalDateTime.parse(fechaFinal).toInstant(ZoneOffset.UTC));
}

builder.put("fecha").greaterThan(dateI).lessThan(dateF);

List<DBObject> dbo = bitacoraEjercicios.find(builder.get()).toArray();
return dbo.toString();

Thanks.

Create date objects that represent the date ranges, MongoDB will transform them into an ISODate:

var start = new Date(2015, 1, 3, 1, 0),
    end = new Date(2015, 10, 22, 1, 0); 
db.collection.find({ "fecha": { "$gt": start, "$lt": end }})

I guess there are something wrong in your builder, maybe it generates some incorrect query. $data is not supported by mongo query. Please see this Date query with ISODate in mongodb doesn't seem to work

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