Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Get last created document in Mongodb using Spring Data repository

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();
}
like image 856
p.streef Avatar asked Jan 05 '23 15:01

p.streef


1 Answers

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.

like image 66
Andriy Simonov Avatar answered Jan 17 '23 05:01

Andriy Simonov