p.streef
p.streef

Reputation: 3815

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();
}

Upvotes: 6

Views: 11445

Answers (1)

Andriy Simonov
Andriy Simonov

Reputation: 1288

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.

Upvotes: 9

Related Questions