I'm trying to get the created datetime of the last created item in a mongodb repository.
I could obviously use a findAll(Sort sort) function, and get the first element, but this would not be very practical on a large database.
Mongo queries do not support an "orderBy" query method so this is also not a solution.
The order of creation is in chronological order of "created" so if I can get the last created document in the collection that would be good too.
So my question is: What is the best way to retrieve the last created document in a mongodb repo using Spring data?
My current code:
@Data
@Document
public class Batch
{
@Id
String id;
LocalDateTime created;
//other stuff
}
public interface BatchRepository extends MongoRepository<Batch,String>
{
//this does not work
//Batch findOneOrderByCreatedDesc();
}
Try the following one, it should work well
public interface BatchRepository extends MongoRepository<Batch,String>
{
Batch findTopByOrderByCreatedDesc();
}
Notice that the method name slightly differs from your variant, this difference is important as spring parses the method name and builds a query based on the result of parsing.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With