Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to sort results from MongoTemplate.findAll()?

I currently have a query that returns all the documents in a collection using the findAll() method of MongoTemplate. I want to sort these results, but do not see any way to do so. I see that I can use find() with a Query argument and call .with(Sort sort), but in this scenario, how do I set the Query to return all documents? I would be okay with using either approach.

like image 956
Joseph Blair Avatar asked Dec 11 '22 20:12

Joseph Blair


2 Answers

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

List<MyClass> myClassList=  mongoTemplate.find(query, MyClass.class);
like image 128
niraj darji Avatar answered Dec 28 '22 07:12

niraj darji


An empty Query will behave as findAll(). Like you can write in the mongo shell: db.myCollection.find({}) you can write an emypty Query in the java mongdb driver.

An working sample code would be:

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);
}
like image 21
Konrad Lötzsch Avatar answered Dec 28 '22 08:12

Konrad Lötzsch