MongoTemplatede的两张表关联分页查询
解决方法:
livevideo表有_id字段,order表的produceId字段保存着livevideo表_id值
LookupOperation lookupToLots = LookupOperation.newLookup().
from("order").//关联表名,多方
localField("_id").//关联字段,
foreignField("produceId").//主表关联字段对应的次表字段
as("groups");//查询结果集合名,相当livevideo表数据的一个临时属性,封装order的数据
UnwindOperation unwind = Aggregation.unwind("groups");
//主表
Criteria livevideoCri =new Criteria();
livevideoCri.and("status").is(1);
livevideoCri.and("groups.produceType").is(1);
AggregationOperation match = Aggregation.match(livevideoCri);
// 构建 Aggregation
Aggregation aggregation = Aggregation.newAggregation(lookupToLots,
unwind,match,Aggregation.sort(new Sort(new Sort.Order(Sort.Direction.DESC, sortName))),Aggregation.skip(0),
Aggregation.limit(10));
long count=template.aggregate(Aggregation.newAggregation(lookupToLots,unwind ,match), "livevideo", Livevideo.class).getMappedResults().size();
// 执行查询
List<Document> livevideo = template.aggregate(aggregation, "livevideo", Document.class).getMappedResults();