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.
Query query = new Query();
query.with(new Sort(Sort.Direction.DESC, "_id"));
List<MyClass> myClassList= mongoTemplate.find(query, MyClass.class);
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);
}
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With