mongoTemplate的多表关联查询

一、使用场景

购物车表-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)])]
评论 1
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包

打赏作者

just路人周

你的鼓励将是我创作的最大动力

¥1 ¥2 ¥4 ¥6 ¥10 ¥20
扫码支付:¥1
获取中
扫码支付

您的余额不足,请更换扫码支付或充值

打赏作者

实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值