简体   繁体   中英

Spring Boot MongoRepository query via Date with Criteria lt & gte gives wrong result

When I query MongoRepository via Date field with Criteria in a Spring Boot application, the result is wrong. Here is my method:

Query query = new Query(new Criteria().andOperator(
    Criteria.where("id").is(filter.getId()),
    Criteria.where("datas.ts").lt(filter.getEndTime()).gte(filter.getStartTime())
));

List<PhaseData> phaseDatas = mongoOperations.find(query, PhaseData.class);
List<Data> result = new ArrayList<Data>();

for(Data pData : phaseDatas) {
    result.addAll(pData.getDatas());
}

return result;

When I query with

{ "id" : "1234", "startTime" : "2016-08-04 12:00", "endTime" : "2016-08-04 15:00" }

it gives me records with hour 16:54 & 21:12 too. How can I solve this issue?

Not sure if this addresses your question directly.

The DB won't return wrong result to the query. So I think it could be one of the following things:

  1. It could be that the when you view the documents in mongodb, it displays date in iso format. So view the documents in the same format as you are creating dates for your query.
  2. It could be timezone issue.

Mongodb dates can be considered as ISODate ( MongoDB Date )

When you query, you create date objects in your timezone. So as a first debugging measure, I would see if both my DB and query timezones are the same.

Also, probably it would help if you query by creating date objects in ISODate by using SimpleDateFormat(SDF is not thread safe).

I have found that it could be confusing because the dates that you send are in a different format and the documents that you visually see in mongodb tool are displaying dates in iso format. I think that it could be the issue. The results are good, but probably you are viewing the two things differently and it causes the confusion.

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