Arpan Jain
Arpan Jain

Reputation: 23

Spring Mongo Paging with sorting with MongoRepository

Document Structure - message{obj_id,post_id,message_time,message_text} and @key is obj_id.

Problem Statement: I just want that fetch all the data contains post_id: 'anything' with sorts on the basis of message_time and want custom paging in the result every time. Now I am implementing code mentioned below according to link:https://stackoverflow.com/a/10077534/9901300. But couldn't find where should I give different post_id every time to search result for.

Please look over below code.

public interface MessageMongoRepository extends 
MongoRepository<Message, String> {

@Query("{ 'post_id' : ?0 }")
Page<Message> findByPostIdSorted(Pageable pageable);
}

Service:

@Override
public List<Message> getByPostId(String PostId, int page, int size) {
    List<Message> messages = new ArrayList<>();
    @SuppressWarnings("deprecation")
    PageRequest request = new PageRequest(page, size, new Sort(Sort.Direction.DESC, "message_time"));
    messages = messageRepository.findByPostIdSorted(request).getContent();
    return messages;
}

Upvotes: 2

Views: 5912

Answers (1)

Kency Kurian
Kency Kurian

Reputation: 302

I think this is what you are looking for :

Repository:

@Query("{ 'post_id' : ?0 }")
Page<Message> findByPostId(String postId, Pageable pageable);

Service

messages = messageRepository.findByPostId(postId, request).getContent();

You can just pass the postId to the method defined in the repository

Upvotes: 4

Related Questions