Mongodb 内嵌文档中数组属性的更新和插入

Mongodb 内嵌文档中数组属性的更新和插入

网上资料找的头疼,自己看文档弄个demo,做个笔记总结一下吧。
1、引入对应依赖

 <dependency>
            <groupId>org.springframework.boot</groupId>
            <artifactId>spring-boot-starter-data-mongodb</artifactId>
</dependency>

2、javaBean对象

@Data
public class Goods {

    private long id;

    String name;

    String price;

    List<GoodsAttribute> goodsAttributes;

}
@Data
public class GoodsAttribute {
    String name;
    String describe;
}

3、插入mongodb

 @Test
    public void creatList() {
        List<Goods> list = new ArrayList<>();
        for (int i = 0; i < 10; i++) {
            Goods goods = new Goods();
            List<GoodsAttribute> goodsAttributes = new ArrayList<>();
            for (int j = 0; j < 10; j++) {
                GoodsAttribute goodsAttribute = new GoodsAttribute();
                goodsAttribute.setDescribe("描述" + j);
                goodsAttribute.setName("属性名称" + j);
                goodsAttributes.add(goodsAttribute);
            }
            goods.setId(i);
            goods.setGoodsAttributes(goodsAttributes);
            goods.setName("Tset" + i);
            list.add(goods);
        }
        mongotemplate.insert(list, Goods.class);
    }

4、更新商品id为0 中描述为“描述0” 的子数组

 /**
     * 修改子元素数组属性
     */
    @Test
    public void updateList() {

        Update update = new Update();
        update.set("goodsAttributes.$.name", "11111");
        Query query = Query.query(new Criteria().andOperator(Criteria.where("id").is(0), Criteria.where("goodsAttributes").elemMatch(Criteria.where("describe").is("描述0"))));
        mongotemplate.updateFirst(query, update, Goods.class);
    }

5、插入商品id为0 的新属性test1

 /**
     * 插入更新子元素数组
     */
    @Test
    public void upsertList() {

        Query query = Query.query(new Criteria().andOperator(Criteria.where("id").is(0)));
        GoodsAttribute goodsAttribute = new GoodsAttribute();
        goodsAttribute.setDescribe("test1");
        goodsAttribute.setName("test1");
        Update update = new Update().addToSet("goodsAttributes",goodsAttribute );
        mongotemplate.upsert(query, update, Goods.class);
    }

6、删除商品id为0的 属性名称为1

 /**
     * 删除子元素数组
     */
    @Test
    public void deleteList() {
        Update update = new Update();
        update.pull("goodsAttributes", new BasicDBObject("name", "属性名称1"));
        Query query = Query.query(Criteria.where("id").is(0));
        mongotemplate.updateFirst(query, update, Goods.class);
    }
  • 0
    点赞
  • 3
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

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

余额充值