我需要获取最后插入的客户端,以便我可以创建一个连续的 id,我尝试了带有以下路径的 @Query 注释,但它不运行应用程序。
public interface ClienteRepository extends MongoRepository<Cliente, String> {
@Query("[{ $sort: ({ _id: -1}).limit:(1)}]")
Cliente findLastCliente();
}```
Caused by: org.springframework.beans.factory.BeanCreationException: Error creating bean with name 'clienteRepository': Invocation of init method failed; nested exception is com.mongodb.util.JSONParseException:
[{ $sort: ({ _id: -1}).limit:(1)}]
最佳答案
你可以通过三种方式做到这一点
1:直接使用这个。 Spring将自动为您创建所需的查询
Cliente findTopByOrderByIdDesc();
2:您可以使用Pageable,但只能获取1条记录。
@Query(sort = "{ _id : -1 }");
Page<Cliente> findByMethod(Pageable pageable);
// Inside service
Page fooPage = FooRepository.findByMethod('John', new PageRequest(0,1));
3:自定义查询
Query query = new Query();
query.limit(1);
query.with(new Sort(Sort.Direction.DESC, "_id"));
mongoOperation.find(query, Cliente.class);
我更喜欢第一个选项
顺便说一句,您遇到的问题是因为此 @Query("[{ $sort: ({ _id: -1}).limit:(1)}]")
不在正确的 JSON 格式,可以转换为 Mongo Query。
关于java - 获取mongodb java中最后插入的文档,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/58238104/