'How to fetch data from mongoDB based on two dates in spring boot?

I'm using Aggregation in spring boot. but getting response as null

Aggregation.match(Criteria.where("createdAt").lt(fromDate).gt(toDate));

mongoDbTemplate returning query as follows

"createdAt" : { "$gt" : { "$date" : "2020-12-31T18:30:00.000Z"} , "$lt" : { "$date" : "2022-01-04T07:34:42.000Z"}}}}

so how to fetch data from MongoDB using mongoTemplate.aggregation. $date is not supported in mongo Shell, is there any solution for this?



Solution 1:[1]

Try to understand the build-in methods you can create by functions names

@Repository
public interface YourDTORepository extends MongoRepository<YourDTO, YourIdentifier> {
    ArrayList<YourDTO> findByCreatedAtBetween(LocalDateTime from, LocalDateTime to);
}

Between expecting for two parameters and it will build the range for you.

Solution 2:[2]

You need to use and in case you want to get range [from,to]

Aggregation.match(Criteria.where("createdAt").lt(fromDate)
                                     .and("createdAt").gt(toDate));

Alternatively,

Criteria class has andOperator function. You need to pass your conditions to that.

query.addCriteria(
    new Criteria().andOperator(
        Criteria.where("createdAt").lt(fromDate),
        Criteria.where("createdAt").gt(toDate)
    )
);

Another option is query annotation.

@Query("{'createdAt' : { $gte: ?0, $lte: ?1 } }")

Here, ?0 represents first argument to the function, ?1 represents second argument to the function.

Reference

Solution 3:[3]

After lots of researh finally, I got the solution, probably this will help others.

"createdAt" : { "$gt" : { "$date" : "2020-12-31T18:30:00.000Z"} , "$lt" : { "$date" : "2022-01-04T07:34:42.000Z"}}}}

This is returned by mongoDbTemplate is right but it's not supporting the older version of spring boot.

My project older version was

<pom>
    <groupId>com.Demo</groupId>
    <artifactId>emp</artifactId>
    <version>0.0.1-SNAPSHOT</version>
    <packaging>war</packaging>
</pom>

I change it as follows

 <pom>
        <groupId>com.Demo</groupId>
        <artifactId>emp</artifactId>
        <version>2.5.3</version>
        <packaging>war</packaging>
  </pom>

The rest of the code is the same as above.

So it's working fine.

Sources

This article follows the attribution requirements of Stack Overflow and is licensed under CC BY-SA 3.0.

Source: Stack Overflow

Solution Source
Solution 1 4EACH
Solution 2 4EACH
Solution 3 Uttam Pawar