Issue
Could you please help me on how to use @Query in Spring Data Mongodb to find data using Date ?
I have provided my code below:
Repository Class:
public interface CustomerRepository extends MongoRepository<Customer, String> {
@Query("{ 'createdDateTime' : { $gt: ?0 } }")
List<Customer> findAllCustomersByCreatedDate(Date date);
}
ServiceImpl Class:
@Service("CustomerService")
public class CustomerServiceImpl implements CustomerService {
public List<Customer> findAllCustomersByCreatedDate(String createdDate) throws ParseException {
return customerRepository.findAllCustomersByCreatedDate(new SimpleDateFormat("YYYY-MM-DD").parse(createdDate));
}
}
RestController Class:
@RestController
@RequestMapping("customers")
public CustomerController {
@Autowired
private CustomerService customerService;
@RequestMapping(value = "/byCreatedDate", method = RequestMethod.GET, produces = { "application/json;charset=UTF-8" })
public ResponseEntity<List<Customer>> findAllCustomersByCreatedDate(@RequestParam String createdDate)
throws BusinessException, ParseException {
List<Customer> customers = customerService.findAllCustomersByCreatedDate(createdDate);
return ResponseEntity.status(HttpStatus.OK).body(customers);
}
}
Data inside Mongo database for customers collection:
{ "_id" : ObjectId("57851d1ee59782560e77ac3f"),
"_class" : "com.myproject.models.Customer",
"name" : "Rob",
"createdBy" : "John",
"createdDateTime" : ISODate("2016-07-12T16:38:54.439Z")
}
{ "_id" : ObjectId("5786222b29b42251b16b5233"),
"_class" : "com.myproject.models.Customer",
"name" : "Sara",
"createdBy" : "John",
"createdDateTime" : ISODate("2016-07-13T08:38:52.116Z")
}
If I invoke the below URL with date string as "2016-07-19T14:38:54.439Z", it still returns 2 results (above 2 documents) even though there are no records created after 2016-07-19 in database.
http://localhost:8080/projects/byCreatedDate?createdDate=2016-07-19T14:38:54.439Z
What is the problem with my code above ? Could you please help ?
How Can I correct my code above to handle dates with Mongodb ?
Solution
I have spotted the problem which is the incorrect date format and changed the ServiceImpl class code as below, now the documents are fetched as expected:
return customerRepository.findAllCustomersByCreatedDate(
new SimpleDateFormat("yyyy-MM-dd'T'HH:mm:ss.SSS'Z'").parse(createdDate)
);
Answered By - developer
Answer Checked By - Gilberto Lyons (JavaFixing Admin)