Jos*_*air 2 spring-data-mongodb
我目前有一个查询,使用MongoTemplate的findAll()方法返回集合中的所有文档.我想对这些结果进行排序,但看不到任何方法.我看到我可以使用带有Query参数的find()并调用.with(排序排序),但在这种情况下,如何设置Query以返回所有文档?我可以使用任何一种方法.
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)
空查询的行为与 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)
| 归档时间: |
|
| 查看次数: |
11899 次 |
| 最近记录: |