Reputation: 2413
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.
Upvotes: 1
Views: 2153
Reputation: 103375
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);
Upvotes: 4