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?
CodePudding user response:
You need to use and
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.
CodePudding user response:
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.
