skip to Main Content

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

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

2

Answers


  1. You are trying to compare the whole date, with the value of the month, which won’t match, hence you get 0 results. If you have stored date values as strings, you can use $regex, like this:

    public List<Employees> getEmployees(){
        Query query = new Query();
        query.addCriteria(Criteria.where("registrationDate").regex("^\d{4}-02-\d{2}"));
        return mongoTemplate.find(query, Visit.class);
    }
    

    Playground link.

    Login or Signup to reply.
  2. I think you are looking for a query like this one so you can try something like this:

    Aggregation aggregation = Aggregation.newAggregation(
        match(Criteria.where("date").month().equalTo(2)));
    return mongoTemplate.aggregate(aggregation, "collection", Visit.class).getMappedResults();
    
    Login or Signup to reply.
Please signup or login to give your own answer.
Back To Top
Search