如何从MongoTemplate.findAll()中排序结果?

Jos*_*air 2 spring-data-mongodb

我目前有一个查询,使用MongoTemplate的findAll()方法返回集合中的所有文档.我想对这些结果进行排序,但看不到任何方法.我看到我可以使用带有Query参数的find()并调用.with(排序排序),但在这种情况下,如何设置Query以返回所有文档?我可以使用任何一种方法.

nir*_*rji 7

Query query = new Query();
query.with(new Sort(Sort.Direction.DESC, "_id"));

List<MyClass> myClassList=  mongoTemplate.find(query, MyClass.class);
Run Code Online (Sandbox Code Playgroud)

  • 这在最近的版本中可能已经改变,但“Sort”的构造函数(现在)是私有的。我的领域不同,但我使用 `Sort.by("_id").descending()` 代替。 (3认同)

Kon*_*sch 3

空查询的行为与 findAll() 相同。就像您可以在 mongo shell 中编写一样: db.myCollection.find({}) 您可以在 java mongdb 驱动程序中编写一个 emypty 查询。

一个工作示例代码是:

public static void main(String[] args) throws UnknownHostException
{
    ServerAddress address = new ServerAddress("localhost", 27017);
    MongoClient client = new MongoClient(address);
    SimpleMongoDbFactory simpleMongoDbFactory = new SimpleMongoDbFactory(client, "mydatabase");
    MongoTemplate mongoTemplate = new MongoTemplate(simpleMongoDbFactory);
    Query query = new Query().with(new Sort("_id", "-1"));
    List<MyClass> allObjects = mongoTemplate.find(query, MyClass.class);
    System.out.println(allObjects);
}
Run Code Online (Sandbox Code Playgroud)