The goal
I'd like to have this query:
db.getCollection("employees").find().sort({
hire_date: 1
}).limit(10)
written with MongoTemplate in Spring Boot.
The research
I've seen many posts and sites about sorting like e.g.
- https://www.baeldung.com/java-mongodb-aggregations
- Spring + MongoDB - MongoTemplate + Criteria Query
- Spring MongoDB query sorting
Attempts
I've tried many ways but I still can't figure out how can I have this done. Some of the things I've tried are listed below:
@Service
public class MongoService {
@Autowired
private MongoTemplate mongoTemplate;
public Document simpleQuery() {
// 1st
mongoTemplate.aggregate(Arrays.asList(
sort(Sorts.ascending("hire_date")),
limit(10)
));
// 2nd
mongoTemplate.findAll(Employee.class).sort(new BasicDBObject("hire_date", 1));
// 3rd
mongoTemplate.findAll(Employee.class).sort((o1, o2) -> o1.getHire_date() > o2.getHire_date());
// and more...
}
}
The solution might be pretty simple I guess, just like the query itself, but these are my first steps on that kind of ground. Thank you in advance for any help on this one.