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);
}