Abhishek saini
Abhishek saini

Reputation: 527

Not getting accurate result in mongodb using gte and lte query

This is my user collection in mongodb

{
    "_id" : NumberLong(104060),
    "age" : 41,
    "username" : "[email protected]",
    "roles" : [
        "ROLE_USER"
    ],
    "firstName" : "Apurva",
    "lastName" : "Shah",
    "email" : "[email protected]",
    "createdDate" : ISODate("2016-02-08T12:23:02.001Z"),
}

i am using criteria like this

criteria = new Criteria().orOperator(name, email)
            .andOperator(genderCriteria).and("_id").ne(id).and("createdDate").gte(startDate).lte(endDate);

when i am passing startdate and enddate like:

Start date is::2015-12-16T00:00:00.000+05:30
end date is::2016-02-08T00:00:00.000+05:30

this user is not coming ,but when i change my enddate to

end date is::2016-02-09T00:00:00.000+05:30

then it is coming. If i am using gte and lte then it must include the date equal to also .Like,when i pass the date from 16 dec to 8 feb, then it is giving all the users with created date 16 to 7 feb. not including the user with created date 8 feb,and when i am passing 16 dec to 9 feb then it include 8 feb user.Is anything am doing wrong i am confuse.Please help. Thank you.

Upvotes: 2

Views: 941

Answers (1)

Sarath Krrish
Sarath Krrish

Reputation: 221

You won't get results for this

Start date is::2015-12-16T00:00:00.000+05:30
end date is::2016-02-08T00:00:00.000+05:30

Check the created Date for user it is ISODate("2016-02-08T12:23:02.001Z") date is equal but not the time.Overall your user date is not in your range .Mongo it checks for both date and time equality.

The one solution you can have is at your application side add additional time 24*60*60 - 1 to this Date createdDate using DateUtils in org.apache.commons.lang.time(Apache Commons Lang)

DateUtils.addSeconds(createdDate,24*60*60-1);

Important Assuming that you will send only date in request.You have to add above code to pre proprocess your request object but not when your inserting.When ever a request comes add this piece of code.It will work fine

Upvotes: 3

Related Questions