使用Spring Data存储库在Mongodb中获取最后创建的文档

p.s*_*eef 3 spring mongodb spring-data

我正在尝试在mongodb存储库中获取最后创建的项目的创建日期时间.

我显然可以使用findAll(排序排序)函数,并获取第一个元素,但这在大型数据库上不太实用.

Mongo查询不支持"orderBy"查询方法,因此这也不是解决方案.

创建的顺序是按照"创建"的时间顺序排列的,所以如果我可以在集合中获得最后创建的文档也是好的.

所以我的问题是:使用Spring数据在mongodb仓库中检索最后创建的文档的最佳方法是什么?

我目前的代码:

@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();
}
Run Code Online (Sandbox Code Playgroud)

And*_*nov 7

尝试以下一个,它应该工作得很好

public interface BatchRepository extends MongoRepository<Batch,String>
{
    Batch findTopByOrderByCreatedDesc();
}
Run Code Online (Sandbox Code Playgroud)

请注意,方法名称与您的变体略有不同,这种差异非常重要,因为Spring会解析方法名称并根据解析结果构建查询.