2

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.

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.

big_OS
  • 381
  • 7
  • 20

2 Answers2

1

Try this,

Aggregation aggregation = Aggregation.newAggregation(
    sort(Sort.Direction.ASC, "hire_date"),
    limit(10)
).withOptions(AggregationOptions.builder().allowDiskUse(Boolean.TRUE).build());

mongoTemplate.aggregate(aggregation, mongoTemplate.getCollectionName(Employee.class), Object.class).getMappedResults();
varman
  • 8,704
  • 5
  • 19
  • 53
  • yes, it helped :) but there is one weird behaviour - it wouldn't let me use `allowDiskUse` when I tried to write it by myself but when I copy-pased your answer, it worked – big_OS Aug 22 '20 at 08:26
  • let me know why are we using `allowDiskUsage` here? – big_OS Aug 22 '20 at 08:27
  • 1
    thank you. This https://stackoverflow.com/a/37805720/7975771 answer has clear explanation. Let me know if you have any doubts. I will try my best to sort it out – varman Aug 22 '20 at 08:31
1

You can do as below.

  1. You need a query part
//As you need to match all
Query query = new Query()
  1. You need to add sorting option
//You need to use Sort class with sorting order, field name to be used for sorting
query.with(new Sort(Sort.Direction.ASC, "hire_date"));
  1. You need to add pagination option
final Pageable pageableRequest = PageRequest.of(0, 10);
query.with(pageableRequest);
  1. You need to add a model
mongoTemplate(query, Employee.class)

Sample refer

Another useful answer

Gibbs
  • 21,904
  • 13
  • 74
  • 138