【问题标题】:Get last created document in Mongodb using Spring Data repository使用 Spring Data 存储库在 Mongodb 中获取最后创建的文档
【发布时间】:2016-08-02 09:42:00
【问题描述】:

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

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

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

【问题讨论】:

    标签: spring mongodb spring-data


    【解决方案1】:

    试试下面的,应该可以的

    public interface BatchRepository extends MongoRepository<Batch,String>
    {
        Batch findTopByOrderByCreatedDesc();
    }
    

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

    【讨论】:

    • findTopByOrderByCreatedDesc(); -> findTop1ByCreatedDesc();
    猜你喜欢
    • 1970-01-01
    • 2019-01-29
    • 1970-01-01
    • 2012-06-21
    • 1970-01-01
    • 2013-05-18
    • 2014-09-11
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多