3

I want to sort the results of a find using the mongo JSON query and having done some reading and experimenting, I still can't get it to work. I have got the PagingAndSortingRepository and can use Sort() on findAll with no problems.

Repository class

public interface ThingRepository extends PagingAndSortingRepository<Thing, ObjectId> {
    @org.springframework.data.mongodb.repository.Query("{ name:?0, $or : [ { state:'new' } , {state:'updated'} ] }")
    List<Device> findThingsInNewOrUpdatedState(String name);
}

Service layer

@Service
public class ThingService() {
    @Autowired private ThingRepository thingRepository;

    public List<Thing> getSortedThings() {
        return (List<Thing>)thingRepository.findAll(new Sort(Sort.Direction.DESC, Arrays.asList("dateModified")));
    }

    public List<Thing> getNewOrUpdatedThingsSorted() {
        return thingRepository.findThingsInNewOrUpdatedState(); // <-- this needs to be sorted
    }
}

The query is translated directly into the mongoDb call, which works fine

db.things.find({ name:'xxx', $or : [ { state:'new' }, {state:'updated'} ] })

and I know I can add a sort() 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 find().

1 Answer 1

5

You should be able to simply add a Sort parameter to the query method and thus dynamically pipe in Sort instances that will be applied to the query defined in @Query.

Sign up to request clarification or add additional context in comments.

9 Comments

Hmm, I'm pretty sure I tried that, but I might be wrong. I will give it another go later today and get back to you.
Sorry, only just got round to trying this. The sorting is working fine as a parameter to the method, e.g. List<Thing> findByThingId(String thingId, Sort sort); but I cannot use the Sort with an annotated custom query, e.g. @org.springframework.data.mongodb.repository.Query. Any ideas?
So you say piping in the Sort does not have effect as soon as you manually define the query using @Query? If that's the case please open a JIRA ticket.
Bug fixed. Will be available in tonight's snapshot as well as the upcoming 1.0 RC1 release.
No,please re-read the comments. The method declaration is shown above. Annotate this one with @Query("{ 'name' : ?0 }") and hand a new Sort(Order.ASC, "age") to the method.
|

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.