Joseph Blair
Joseph Blair

Reputation: 1455

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.

Upvotes: 5

Views: 31855

Answers (3)

Pierre Houry
Pierre Houry

Reputation: 21

The syntax is now:

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

List<MyClass> myClassList=  mongoTemplate.find(query, MyClass.class);

Upvotes: 1

niraj darji
niraj darji

Reputation: 339

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

List<MyClass> myClassList=  mongoTemplate.find(query, MyClass.class);

Upvotes: 11

Konrad L&#246;tzsch
Konrad L&#246;tzsch

Reputation: 478

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);
}

Upvotes: 3

Related Questions