一、使用场景

购物车表-car

在这里插入图片描述

购物车中的商品表

在这里插入图片描述

需要在查询car表的时候根据carId带出下面关联的商品

二、代码实现

pojo

@Data
@Document(collection = "car")
@AllArgsConstructor
@NoArgsConstructor
public class Car implements Serializable {
    @Id
    private String id;
    private String shopName;
    private Integer wxUserId;
    private Integer sellerId;
    private Integer sellerWxId;
    private Long createTime;
    private Long updateTime;
    private List<CarOid> oid;// 注意这...
}

查询方法:

public List<Car> findAll(Integer wxUserId) {
        Criteria criteria = Criteria.where("wxUserId").is(wxUserId);
        Aggregation aggregation = Aggregation.newAggregation(
                Aggregation.match(criteria),
                /*关联oid 参数1-子集合的名称,参数2-父表id,参数3-字表关联父表的外键,参数4-查询子结合后给的别名as*/
                Aggregation.lookup("car_oid", "_id", "carId", "oid"),
                /*排序*/
                Aggregation.sort(Sort.by(Sort.Order.desc("createTime")))
        );
		Aggregation.newAggregation(Aggregation.match(criteria),lookupOperation);
        List<Car> cars = mongoTemplate.aggregate(aggregation, "car",
                Car.class).getMappedResults();
        return cars;
    }

三、测试结果

 	@Test
    public void find()
    {
        List<Car> carList = carService.findAllPage(7);
        System.out.println(carList);
    }
    // 输出 [Car(id=1540320098076995584, shopName=小爱店铺, wxUserId=7, sellerId=30, sellerWxId=6, createTime=1656075903, updateTime=1656083373, oid=[CarOid(id=1540328132346003456, carId=1540320098076995584, wxUserId=7, sellerId=31, sellerWxId=6, createTime=1656077819, updateTime=1656077847, skuId=65, title=【赠充电器】HUAWEI/华为 P50 HarmonyOS2原色双影像单元新款华为智能手机新款华为官方旗舰店p50pro, sku1Name=null, sku2Name=null, sku1Value=雪域白, sku2Value=8+128GB, pic=CNVho38U5PSz248811149531a662b07b42fd6b26edd6.png, num=8), CarOid(id=1540351428735246336, carId=1540320098076995584, wxUserId=7, sellerId=30, sellerWxId=6, createTime=1656083373, updateTime=1656083373, skuId=66, title=【赠充电器】HUAWEI/华为 P50 HarmonyOS2原色双影像单元新款华为智能手机新款华为官方旗舰店p50pro, sku1Name=null, sku2Name=null, sku1Value=雪域白, sku2Value=8+256GB, pic=CNVho38U5PSz248811149531a662b07b42fd6b26edd6.png, num=4)])]
Logo

为开发者提供学习成长、分享交流、生态实践、资源工具等服务,帮助开发者快速成长。

更多推荐