To implement the MongoDB results pagination in Java, there are few parameters that need to be collected:
1) the order of results (ascending / descending)
2) the field used to order the results
3) the number of element and the page selected
4) the field and the value used to filter the results
As well as the results of query, the method needs to return the total number of elements. All returned elements will be saved in a HashMap.
HashMap<String, Object> resultMap = new HashMap<String, Object>();
Direction direction = Sort.DEFAULT_DIRECTION;
if (sortDirection > 0) {
direction = Sort.Direction.ASC;
} else {
direction = Sort.Direction.DESC;
}
List |
HashMap<String, Object> resultMap = new HashMap<String, Object>();
Direction direction = Sort.DEFAULT_DIRECTION;
if (sortDirection > 0) {
direction = Sort.Direction.ASC;
} else {
direction = Sort.Direction.DESC;
}
List
If a pagination is required, skip and limit are used
if (pageSize > 0) {
query.skip((pageNum - 1 ) * pageSize);
query.limit(pageSize);
}
if ( sortField != null && !sortField.equals("") ) {
query.with(new Sort(direction, sortField));
}
results = mongoTemplate.find(query, Object.class); |
if (pageSize > 0) {
query.skip((pageNum - 1 ) * pageSize);
query.limit(pageSize);
}
if ( sortField != null && !sortField.equals("") ) {
query.with(new Sort(direction, sortField));
}
results = mongoTemplate.find(query, Object.class);
If a pagination is required, queryCounter (basically a version of query without pagination an limit) is used to calculate the total number of results. Of course, if pagination is not required, is possible to use directly the size of results.
if ( pageSize > 0 ) {
resultMap.put("RESULT_SIZE", (int) mongoTemplate.count(queryCounter, Object.class));
} else {
// If pagination is not required, the query is not re-executed
resultMap.put("RESULT_SIZE", results.size());
} |
if ( pageSize > 0 ) {
resultMap.put("RESULT_SIZE", (int) mongoTemplate.count(queryCounter, Object.class));
} else {
// If pagination is not required, the query is not re-executed
resultMap.put("RESULT_SIZE", results.size());
}
mongoTemplate is a spring bean defined in this way on context configuration:
<bean id="mongoTemplate" class="org.springframework.data.mongodb.core.MongoTemplate" c:mongo-ref="mongo" c:databaseName="${mongo.db.name}">
<property name="writeConcern" value="SAFE" />
</bean> |
<bean id="mongoTemplate" class="org.springframework.data.mongodb.core.MongoTemplate" c:mongo-ref="mongo" c:databaseName="${mongo.db.name}">
<property name="writeConcern" value="SAFE" />
</bean>