我在 spring 数据中使用 TypedAggregation 和 mongoTemplate 来对结果集进行排序和限制。
import static org.springframework.data.mongodb.core.aggregation.Aggregation.limit;
import static org.springframework.data.mongodb.core.aggregation.Aggregation.match;
import static org.springframework.data.mongodb.core.aggregation.Aggregation.newAggregation;
import static org.springframework.data.mongodb.core.aggregation.Aggregation.project;
import static org.springframework.data.mongodb.core.aggregation.Aggregation.sort;
import org.springframework.data.domain.Sort.Direction;
TypedAggregation<ObjectType> agg = newAggregation(ObjectType.class,
match(matching Criteria),
project("_id", ...),
sort(Direction.ASC, "_id"),
limit(pageSize));
List<RESULT_OBJECT> mappedResult = mongoTemplate.aggregate(agg, COLLECTION_NAME, RESULT_OBJECT.class).getMappedResults();