title: Spring Data MongoDB sort performance
body: <p>I'm seeing significant differences in Spring Data MongoDB sort performance, depending on the direction. I'm sorting on one property and have indices in both directions. When sorting ascending, the response time is around 80 ms, when sorting descending it's around 2.7 s. <strong>Native queries</strong> take 5 ms and 50 ms, respectively. Queries for subsequent pages are somewhat faster, around 1 s.</p>
  
  <p>The 2.7 s is unacceptable for my application, is there anything I can do?</p>
  
  <p>Controller:</p>
  
  <pre><code>String q = URLDecoder.decode(query);
  Sort.Direction d = Sort.Direction.ASC;
  
  if (direction == -1) {
      d = Sort.Direction.DESC;
  }
  
  String[] properties = sort.split(",");
  Sort s = new Sort(d, Arrays.asList(properties));
  Pageable p = new PageRequest(page, size, s);
  
  List&lt;Employer&gt; list = employerRepository.find(q, p);
  </code></pre>
  
  <p>Repository:</p>
  
  <pre><code>@Override
  public List&lt;Employer&gt; find(String query, Pageable page) {
      Query q = new BasicQuery(query).with(page);
      return mongoTemplate.find(q, Employer.class);
  }
  </code></pre>
  
  <p><strong>Update 1:</strong> I have enabled profiling on MongoDB, and the native and Spring Data queries look identical. So it seems the bottleneck is in <code>mongoTemplate.find(q, Employer.class);</code>. </p>