I want to query a mongo collection to fetch documents created before a given date. I use the MongoRepository query findByDateBefore()
. But turns out, it doesn't return any records. Here's my code implementation (pseudo):
MyDocument model
@Document(collection = "mydocument")
public class MyDocument {
@Id
String name;
Date creationDate;
}
The repository:
@Repository
public interface MyDocumentRepository extends MongoRepository<MyDocument, String> {
List<MyDocument> findByCreationDateBefore(Date date);
// @Query("{'creationDate': {"$lt": ?0}}")
// List<MyDocument> findbyCreationDateBefore(Date date)
}
Service code:
java.util.Date today = new Date();
List<MyDocument> documents = myDocumentRepository.findByCreationDateBefore(today);
The query logged after the service call:
MongoTemplate: find using query: { "creationDate" : { "$lt" : { "$date" : "2020-03-12T13:17:23.784Z"}}} fields: null for class: class com.myrepo.model.MyDocument in collection: mydocument
This return no results. I have tried using custom query (commented code in repository) which also doesn't return any records. Also I tried running the logged query in the mongo console and it does not return any results:
{ "creationDate" : { "$lt" : { "$date" : "2020-03-12T13:17:23.784Z"}}}
But when I use new Date, in mongo console, it works fine. e.g.:
{ "creationDate" : { "$lt" : new Date("2020-03-12T13:17:23.784Z")}}
.
Solutions mentioned here doesn't work for me.