Spring Data Mongodb - obtaining last item on a page

2.5k views Asked by At

This is my current pagination method on Spring Data MongoDB:

  @RequestMapping(value="/nextposts", method=RequestMethod.GET)
  public List getNextPosts(@RequestParam int next) {
    Pageable pageable = new PageRequest(next, 5, new Sort(new Sort.Order(Direction.DESC, "id")));
    page = repo.findAll(pageable);
    return page.getContent(); 
  }

As you can see, I'm obtaining the page as specified by the "next" variable and then returning it to the user.

I'm trying to get a handle on the last document returned in the page, specifically to get its ObjectId so I can implement "Approach 2" of fast pagination with mongodb: http://blog.mongodirector.com/fast-paging-with-mongodb/

I have looked on the docs for PageRequest and Pageable but none of the methods will return the last document in the page.

Pageable: http://docs.spring.io/spring-data/data-commons/docs/current/api/org/springframework/data/domain/Pageable.html

PageRequest: http://docs.spring.io/spring-data/data-commons/docs/current/api/org/springframework/data/domain/PageRequest.html

Does anyone know how this can be done?

2

There are 2 answers

0
Simon On BEST ANSWER

Eventually I couldn't do it with the MongoRepository.

I had to use the MongoOperation / MongoTemplate to do this task.

  @RequestMapping(value="/XXX", method=RequestMethod.GET)
  public List getNextPosts(@RequestParam String next) {
      Query query = new Query();
      query.with(new Sort(Sort.Direction.DESC, "_id"));
      query.limit(5);
      ObjectId objID = new ObjectId(next);
      query.addCriteria(Criteria.where("_id").lt(objID));
      List<Posts> posts = mongoOperation.find(query, Posts.class);
      return posts;
  }
1
Hassam Abdelillah On

Simon actually you have to custom some of the pageable logic to get more "features" because i don't think the last item can be got just like that.

Here's is a good exemple where your define your proper page resource model and add some metadata to it. link such as first, last, NEXT rels.

http://www.javaenthusiasm.com/rest-pagination-with-spring-boot/

Tell me if you need more explanations.