一、创建MyRepository接口
在MyRepository中引用MongoTemplate
public interface MyRepository {
Page<Reading> findTest(SUser sUser, Pageable pageable);
}
二、创建实现类MyRepositoryImpl实现MyRepository
包含Aggregate用法
public class MyRepositoryImpl implements MyRepository {
@Autowired
private MongoTemplate mongoTemplate;
@Override
public Page<Reading> findTest(SUser sUser, Pageable pageable) {
ObjectId objectId = new ObjectId(sUser.getId());
Aggregation aggregation = Aggregation.newAggregation(
aoc ->
new Document(
"$addFields",
new Document("user", new Document("$arrayElemAt", Arrays.asList(new Document("$objectToArray", "$user"), 1L)))
),
aoc -> new Document("$addFields", new Document("user", "$user.v")),
Aggregation.match(Criteria.where("user").is(objectId)),
aoc ->
new Document(
"$addFields",
new Document("reading", new Document("$arrayElemAt", Arrays.asList(new Document("$objectToArray", "$reading"), 1L)))
),
aoc -> new Document("$addFields", new Document("reading", "$reading.v")),
Aggregation.lookup("reading", "reading", "_id", "reading"),
aoc -> new Document("$replaceRoot", new Document("newRoot", new Document("$first", "$reading"))),
Aggregation.project(
"id",
"title",
"author",
"genre",
"alignment",
"text_summary",
"clicks",
"language",
"is_private",
"length",
"date_created",
"last_updated",
"uploader",
"tags",
"playlists"
),
Aggregation.sort(pageable.getSort()),
Aggregation.skip(pageable.getPageNumber() * pageable.getPageSize()),
Aggregation.limit(pageable.getPageSize())
);
Aggregation aggregationCount = Aggregation.newAggregation(
aoc ->
new Document(
"$addFields",
new Document("user", new Document("$arrayElemAt", Arrays.asList(new Document("$objectToArray", "$user"), 1L)))
),
aoc -> new Document("$addFields", new Document("user", "$user.v")),
Aggregation.match(Criteria.where("user").is(objectId)),
Aggregation.group().count().as("count")
);
AggregationResults<Reading> readings = mongoTemplate.aggregate(aggregation, "favorite", Reading.class);
int count = mongoTemplate.aggregate(aggregationCount, "favorite", ResultCount.class).getMappedResults().get(0).count;
List<Reading> mappedResults = readings.getMappedResults();
Page<Reading> page = new PageImpl<>(mappedResults, pageable, count);
return page;
}
class ResultCount {
int count;
}
}
三、在Repository继承MyRepositoryImpl实现代码即可
|