MongoDB version - 5.0.5-rc0
Spring Boot version - 2.5.7
Spring Data MongoDB version - 3.2.7
public interface CatalogRepository extends MongoRepository<CatalogModel, Long> {
List<CatalogModel> findByCreatedDateIsBetween(Date fromDate , Date toDate , Pageable pageable);
}
@Document(collection = "catalog")
@Data
public class CatalogModel {
@Id
@Field("skuId")
private Long _id;
...
...
@Field("createdDate")
@Indexed(name="idx_catalog_created_date_v1")
private Date createdDate;
}
Logs generate from spring boot application -
2021-12-25 15:51:16.792 DEBUG 25652 --- [io-10091-exec-3] o.s.d.m.r.query.MongoQueryCreator : Created query Query: { "createdDate" : { "$gt" : { "$date" : "2021-12-22T00:00:00Z"}, "$lt" : { "$date" : "2021-12-23T00:00:00Z"}}}, Fields: {}, Sort: {}
2021-12-25 15:51:16.793 DEBUG 25652 --- [io-10091-exec-3] o.s.data.mongodb.core.MongoTemplate : find using query: { "createdDate" : { "$gt" : { "$date" : "2021-12-22T00:00:00Z"}, "$lt" : { "$date" : "2021-12-23T00:00:00Z"}}} fields: Document{{}} for class: class com.cp.bootmongo.model.CatalogModel in collection: catalog
2021-12-25 15:51:16.794 DEBUG 25652 --- [io-10091-exec-3] org.mongodb.driver.protocol.command : Sending command '{"find": "catalog", "filter": {"createdDate": {"$gt": {"$date": "2021-12-22T00:00:00Z"}, "$lt": {"$date": "2021-12-23T00:00:00Z"}}}, "skip": 1, "limit": 1, "$db": "cpmongodb", "lsid": {"id": {"$binary": {"base64": "wRdxZvvNTsKtZODqaBsxEQ==", "subType": "04"}}}}' with request id 88 to database cpmongodb on connection [connectionId{localValue:8, serverValue:5}] to server localhost:27017
MongoDB compass on the other hand returns results for similar query (pfa)
The only missing point I am not able to understand is how MongoDB server handles “$date” sent in query ? Do we have any better way to achieve date query ?