1

I'm using MongoDB from Java and I've got this line to retrieve some data:

@Query("{'buyerId': ?0, 'status': ?1  }")
Page<CardOrder> getBuyerOrders(final String profileId, final Pageable pageable);

I'd like to sort them by the field 'created'.

{"created": 1}

How can I merge those two queries in the @Query annotation?

(i.e @Query("{'buyerId': ?0, 'status': ?1  }{"created": 1}"))

Thanks.

3
  • 1
    Please post complete java code you are using, are doing it with JPA ? Commented Sep 23, 2015 at 10:16
  • Sorry, I don't wanna sound unpolite, but it's not necessary for this, I just need the query, no need for Java code. Commented Sep 23, 2015 at 10:17
  • this thing cant be managble in query as java have its own parser finally query been converted to native mongo query, sort parameter can be passed through java cod, so code is nessesory. Commented Sep 23, 2015 at 10:21

1 Answer 1

4

Not sure if you can merge the two in the @Query annotation but you can make your repository method use a Sort parameter by adding it to the query method and dynamically pipe in Sort instances that will be applied to the query defined in @Query:

@Query("{ buyerId: ?0, status: ?1 }")
List<Thing> findThingsByUserIdAndStatus(String buyerId, String status, Sort sort);

Call the method:

repository.findThingsByUserIdAndStatus("foo", "ACTIVE", new Sort(Sort.Direction.DESC, "created"));

-- UPDATE --

To sort with Pageable, add the sort instance as a parameter to the Pageable object:

PageRequest request = new PageRequest(0, 1, new Sort(Sort.Direction.DESC, "created"));
repository.getBuyerOrders("foo", request);
Sign up to request clarification or add additional context in comments.

5 Comments

Many thanks for the answer; is that Sort the one coming from import org.springframework.data.domain.Sort;?
Yes, it's from the 1.9.3 RELEASE
Thanks my friend, I'll try it and mark your solution as valid in a bit.
It's not letting me use it unfortunately, looks like Pageable and sort are incompatible: Caused by: java.lang.IllegalStateException: Method must not have Pageable and Sort parameter. Use sorting capabilities on Pageble instead! Offending method. How can I sort with pageable?
I've made an update to the answer, you should be able to use the Pageable object with the sort as a parameter as above.

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.