17

I am trying to search for date of birth using query

criteria = Criteria.where("dob").lte(new DateTime().toDate());

And spring data mongodb generate below query:

MongoTemplate: find using query:

{ "dob" : { "$lte" : { "$date" : "2015-05-16T07:55:23.257Z"}}}

fields: null for class: class com.temp.model.User in collection: user

But I did not get any result.

My dob field in mongodb:

{"dob" : ISODate("1991-01-23T00:00:00Z")}

How I can search for dob in ISODate format ?

0

4 Answers 4

9

This code should work fine for what you need:

criteria = Criteria.where("dob").lte(new java.util.Date());

My test is with following code, which does work fine:

Lis<User> users = mongoOps.find(query(where("isActive").is(true).and("CreatedDate").lte(new java.util.Date())), User.class);
Sign up to request clarification or add additional context in comments.

Comments

7

Query would execute perfect from Spring data mongodb0

{ "dob" : { "$lte" : { "$date" : "2015-05-16T07:55:23.257Z"}}}.

But It will not execute from mongo CLI.

Query to execute on cli.

{dob:ISODate("2015-05-15T07:55:23.257Z")}

Thanks

3 Comments

Work perfectly from Spring mongo Query annotation.
What if we are using JPA MongoRepository? how can we call the $date or isodate without getting a parse exception in @Query annotation?
If there is an index on dob will that be picked since it is translated to $date?
4

For IDE use ISODate() for SPRING DAO convert string to Date object

query.addCriteria(Criteria.where("created").ne(null).andOperator(
                Criteria.where("created").gte(DateUtils.getDate("2016-04-14 00:00:00", DateUtils.DB_FORMAT_DATETIME)),
                Criteria.where("created").lte(DateUtils.getDate("2016-04-14 23:59:59", DateUtils.DB_FORMAT_DATETIME))
            ));


public final class DateUtils {    

    public static final String DB_FORMAT_DATETIME = "yyyy-M-d HH:mm:ss";        

    private DateUtils() {
        // not publicly instantiable
    }       

    public static Date getDate(String dateStr, String format) {
        final DateFormat formatter = new SimpleDateFormat(format);
        try {
            return formatter.parse(dateStr);
        } catch (ParseException e) {                
            return null;
        }
    }



} 

1 Comment

This doesn't deal with T and Z in the date format :(
0
val query = Query()
query.addCriteria( 
Criteria("info.dob").gte(dob.atStartOfDay())

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.