Click here to Skip to main content
15,867,330 members
Please Sign up or sign in to vote.
0.00/5 (No votes)
How can I compare month in spring mongo criteria with a hard corded value, month in criteria is in a spring format and the value is present in an integer format.

This is what i have so far i just want to check for that month and group employee ID if registrationDate repets

What I have tried:

public List<Employees> getEmployees(){
    Query query = new Query();
    query.addCriteria(Criteria.where("registrationDate").is("2"));
    return mongoTemplate.find(query, Visit.class);
    } 


but this returns empty which is not true because I have employees registered on february and registration month in database is stored in this format "2023-02-06 00:00:00.000000"

Any suggestion will be much appreciated
Posted
Updated 13-Mar-23 5:36am
v2
Comments
Richard MacCutchan 13-Mar-23 12:32pm    
Of course it does not match, you are trying to compare "2" with "2023-02-06 00:00:00.000000", which are completely different strings.

1 solution

Think about your query. What does ".is(2)" mean? Is it the month number? The day of the month? How about the yes? Maybe the hour, minutes, or seconds?

How is your code telling the database that the 2 is a month? Hint: It's not.
 
Share this answer
 
Comments
Office Systems 13-Mar-23 12:29pm    
2 represents the month which is february
Dave Kreskowiak 13-Mar-23 12:56pm    
Yeah, YOU know that, and I know that, but the machine does NOT know that. There is nothing in your code that describes the value 2 as a month number.
Dave Kreskowiak 13-Mar-23 13:41pm    
Also, database Date/Time values are not stored with a "format". Are you storing these values in your database tables as strings or as Date/Time values?
Office Systems 13-Mar-23 13:47pm    
The values are stored in database tables as Strings
Dave Kreskowiak 13-Mar-23 13:50pm    
And there is your fatal flaw. NEVER store date/time values are string. You cannot search nor sort on them.

You have to redesign the database and store these values to date/time columns, then it becomes far easier to query again and you don't pay a huge performance penalty by doing string operations in the database.

https://www.mongodb.com/docs/manual/reference/operator/aggregation/month/

This content, along with any associated source code and files, is licensed under The Code Project Open License (CPOL)



CodeProject, 20 Bay Street, 11th Floor Toronto, Ontario, Canada M5J 2N8 +1 (416) 849-8900