MongoTemplate 操作数组字段


import cn.hutool.json.JSONUtil;
import com.google.common.collect.Lists;
import com.mongodb.BasicDBList;
import com.mongodb.BasicDBObject;
import com.mongodb.client.MongoClients;
import lombok.AllArgsConstructor;
import lombok.Data;
import lombok.NoArgsConstructor;
import lombok.extern.slf4j.Slf4j;
import org.junit.jupiter.api.AfterEach;
import org.junit.jupiter.api.BeforeEach;
import org.junit.jupiter.api.DisplayName;
import org.junit.jupiter.api.Test;
import org.springframework.data.annotation.Id;
import org.springframework.data.mongodb.core.MongoTemplate;
import org.springframework.data.mongodb.core.mapping.Document;
import org.springframework.data.mongodb.core.query.Criteria;
import org.springframework.data.mongodb.core.query.Query;
import org.springframework.data.mongodb.core.query.Update;

import java.util.List;

**
 * @author zxp
 * @version 1.0
 * @date 2021/11/1 9:40
 */
@Slf4j
public class MongoArrOptTest {

    private MongoTemplate mongoTemplate;

    @Data
    @Document(collection = "user")
    static class UserEntity {
        @Id
        private String id;

        /**
         * 用户ID
         */
        private Integer userId;
        /**
         * 用户车辆列表
         */
        private List<UserCar> carList;
    }

    @Data
    @AllArgsConstructor
    @NoArgsConstructor
    static class UserCar {
        /**
         * 车牌号
         */
        private String carNo;
        /**
         * 车品牌
         */
        private String carBrand;
    }

    @BeforeEach
    public void before() {

        mongoTemplate = new MongoTemplate(MongoClients.create(), "test");

        // 初始化数据
        UserEntity userEntity = new UserEntity();
        userEntity.setUserId(1);
        userEntity.setCarList(Lists.newArrayList());
        mongoTemplate.insert(userEntity);
    }

    @AfterEach
    public void after() {
        List<UserEntity> all = mongoTemplate.findAll(UserEntity.class);
        System.out.println(JSONUtil.toJsonPrettyStr(all));
        // 删除测试集合
        mongoTemplate.dropCollection(UserEntity.class);
    }



    @Test
    @DisplayName("数组添加一条数据")
    public void push() {
        Query query = new Query(Criteria.where("userId").is(1));
        Update update = new Update();
        update.push("carList", new UserCar("闽A12345", "奥迪"));
        mongoTemplate.updateFirst(query, update, UserEntity.class);
    }


    @Test
    @DisplayName("数组添加多条数据")
    public void pushAll() {
        Query query = new Query(Criteria.where("userId").is(1));
        Update update = new Update();
        update.push("carList").each(Lists.newArrayList(
                new UserCar("闽A11111", "奥迪"),
                new UserCar("闽A22222", "奥迪")));
        mongoTemplate.updateFirst(query, update, UserEntity.class);
    }

    @Test
    @DisplayName("不存在则插入到数组,已存在将不操作")
    public void addToSet() {
        Query query = new Query(Criteria.where("userId").is(1));
        Update update = new Update();
        update.addToSet("carList", new UserCar("闽A11111", "奥迪"));
        // 只会插入一条
        mongoTemplate.updateFirst(query, update, UserEntity.class);
        mongoTemplate.updateFirst(query, update, UserEntity.class);

        log.debug("results: {}", JSONUtil.toJsonPrettyStr(mongoTemplate.findAll(UserEntity.class)));

        update.addToSet("carList").each(Lists.newArrayList(
                new UserCar("闽A11111", "奥迪"),
                new UserCar("闽A22222", "奥迪")));
        mongoTemplate.updateFirst(query, update, UserEntity.class);
    }

    @Test
    @DisplayName("更新数组内的某条记录")
    public void update() {
        // 先插入一些数据
        this.pushAll();

        // 更新车牌号为 闽A22222 的 车辆品牌信息为大众
        Query query = new Query(Criteria
                .where("userId").is(1)
                .and("carList").elemMatch(Criteria.where("carNo").is("闽A22222"))
        );
        Update update = new Update();
        update.set("carList.$", new UserCar("闽A22222", "大众"));
        // 只会插入一条
        mongoTemplate.updateFirst(query, update, UserEntity.class);
    }

    @Test
    @DisplayName("数组删除数据")
    public void pull() {
        // 先插入一些数据
        this.pushAll();

        Query query = new Query(Criteria
                .where("userId").is(1)
        );
        Update update = new Update();
        update.pull("carList", new UserCar("闽A11111", "奥迪"));

        mongoTemplate.updateFirst(query, update, UserEntity.class);
    }

    @Test
    @DisplayName("数组按条件删除指定数据")
    public void pullBy() {
        // 先插入一些数据
        this.pushAll();
        this.pushAll();

        Query query = new Query(Criteria
                .where("userId").is(1)
        );
        Update update = new Update();
        // 删除所有 carNo = 闽A11111 的数据
        update.pull("carList", new BasicDBObject("carNo", "闽A11111"));

        // 删除 carNo 在数组中的数据
        BasicDBList basicDBList = new BasicDBList();
        basicDBList.addAll(Lists.newArrayList("闽A11111", "闽A22222"));
        update.pull("carList", new BasicDBObject("carNo", new BasicDBObject("$in", basicDBList)));

        mongoTemplate.updateFirst(query, update, UserEntity.class);
    }

}

  • 5
    点赞
  • 11
    收藏
    觉得还不错? 一键收藏
  • 1
    评论

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

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

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值