title: Adding sort to mongo JSON @Query with Spring Data Repository
body: <p>I want to sort the results of a <code>find</code> using the <a href="http://static.springsource.org/spring-data/data-document/docs/current/reference/html/#d0e3293" rel="nofollow">mongo JSON query</a> and having done some reading and experimenting, I still can't get it to work. I have got the <a href="http://static.springsource.org/spring-data/data-commons/docs/1.2.0.M1/api/org/springframework/data/repository/PagingAndSortingRepository.html" rel="nofollow">PagingAndSortingRepository</a> and can use <a href="http://static.springsource.org/spring-data/data-commons/docs/1.2.0.M1/api/org/springframework/data/domain/Sort.html" rel="nofollow"><code>Sort()</code></a> on <em>findAll</em> with no problems.</p>
  
  <h3>Repository class</h3>
  
  <pre><code>public interface ThingRepository extends PagingAndSortingRepository&lt;Thing, ObjectId&gt; {
      @org.springframework.data.mongodb.repository.Query("{ name:?0, $or : [ { state:'new' } , {state:'updated'} ] }")
      List&lt;Device&gt; findThingsInNewOrUpdatedState(String name);
  }
  </code></pre>
  
  <h3>Service layer</h3>
  
  <pre><code>@Service
  public class ThingService() {
      @Autowired private ThingRepository thingRepository;
  
      public List&lt;Thing&gt; getSortedThings() {
          return (List&lt;Thing&gt;)thingRepository.findAll(new Sort(Sort.Direction.DESC, Arrays.asList("dateModified")));
      }
  
      public List&lt;Thing&gt; getNewOrUpdatedThingsSorted() {
          return thingRepository.findThingsInNewOrUpdatedState(); // &lt;-- this needs to be sorted
      }
  }
  </code></pre>
  
  <p>The query is translated directly into the mongoDb call, which works fine</p>
  
  <pre><code>db.things.find({ name:'xxx', $or : [ { state:'new' }, {state:'updated'} ] })
  </code></pre>
  
  <p>and I know I can add a <a href="http://www.mongodb.org/display/DOCS/Advanced+Queries#AdvancedQueries-%7B%7Bsort%28%29%7D%7D" rel="nofollow"><code>sort()</code></a> in regular mongoDb syntax but cannot work out how to do this from within Java/Spring Data. It tried adding it to the @Query but it was not working, since I think Spring is just executing a <a href="http://www.mongodb.org/display/DOCS/Querying" rel="nofollow"><code>find()</code></a>.</p>