我需要知道如何找到存储在数据库(最新)上的最后一个对象。我的对象是用时间戳保存的,所以我可以使用这个值来识别哪个是最新的(如果有必要的话),所以存储库中的函数可能看起来像
@Repository
public interface MyObjectRepository extends MongoRepository<MyObject, String> {
MyObject findByNameAndTimesmapt(String name, int timestamp); // I want to get here latest object
}
和对象
public class MyObject {
@Field("name")
private String name;
@Field("timestamp")
private int timestamp;
public MyObject(String name, int timestamp) {
this.name = name;
this.timestamp = timestamp;
}
}
我的函数应该给我与命令相同的结果
db.foo.find("name": "someName"}).sort({"timestamp":-1}).one();
最佳答案
你可以尝试这样的事情。这将以 shell 查询的方式获得结果。以下两种变体都应该可以工作。
MyObject findFirstByNameOrderByTimestampDesc(String name);
或者
MyObject findTopByNameOrderByTimestampDesc(String name);
关于java - Spring 和 MongoDB。查找最后存储的对象,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/41067230/