edwardsbean
edwardsbean

Reputation: 3759

How to pagination with spring data mongo @DBRef

I want to pagination with Spring Data Mongo.From docs spring data mongo can do :

public interface TwitterRepository extends MongoRepository<Twitter, String> {
List<Twitter> findByNameIn(List<String> names, Pageable pageable);
}

If Twitter Document Object like this:

@Document
public class Twitter {
 String name;
 @DBRef
 List<Comment> comments
}

Does spring data mongo support pagination with comments?

Upvotes: 3

Views: 2778

Answers (1)

Robin Rizvi
Robin Rizvi

Reputation: 5183

Note: The code specified is not tested, it will just serve as a pointer for you

The following mongo query limits the the array size to be returned:

db.Twitter.find( {}, { comments: { $slice: 6 } } )

The above mechanism can be used to enforce pagination like so:

db.Twitter.find( {}, { comments: { $slice: [skip, limit] } } )

You can try by annotating your method

@Query(value="{ 'name' : {'$in': ?0} }", fields="{ 'comments': { '$slice': [?1,?2] } }")
List<Twitter> findByNameIn(List<String> names, int skip, int limit);
}

You can specify that in your query like so:

Query query = new Query();
query.fields().slice("comments", 1, 1);
mongoTemplate.find(query, DocumentClass.class);

or you can try and execute the command directly using:

mongoTemplate.executeCommand("db.Twitter.find( {}, { comments: { $slice: [skip, limit] } } )")

General Pagination Mechanisms:

General Pagination mechanisms only work at the document level, examples of which are given below.

For them you will have to manually splice the returned comments at the application level.


If you using the MongoTemplate class (Spring-Data Docs) then:

Use org.springframework.data.mongodb.core.query.Query class's skip() and limit() method to perform pagination

Query query = new Query();
query.limit(10);
query.skip(10);
mongoTemplate.find(query, DocumentClass.class);

If you are using Repository (Spring-Data-Reposioty) then use PagingAndSortingRepository

Upvotes: 2

Related Questions