• MongoDB的搭建 和crud操作


    MongoDB

    docker 下载

    docker run --restart=always -d --name mongo -v /docker/mongodb/data:/data/db -p 27017:27017 mongo:4.0.6
    
    • 1

    使用navcat工具使用MongoDB
    在这里插入图片描述

    Crud操作

    jar包

    <dependency>
                <groupId>org.projectlombokgroupId>
                <artifactId>lombokartifactId>
                <optional>trueoptional>
            dependency>
            <dependency>
                <groupId>org.springframework.bootgroupId>
                <artifactId>spring-boot-starter-data-mongodbartifactId>
            dependency>
    
    • 1
    • 2
    • 3
    • 4
    • 5
    • 6
    • 7
    • 8
    • 9

    实体类

    @Data
    @AllArgsConstructor
    @NoArgsConstructor
    @Builder
    // 作用时与 MongoDB中的206_person对应
    @Document("206_person")
    public class Person {
        @Id
        private Integer id;
        private String  name;
        private Integer girls;
    }
    
    • 1
    • 2
    • 3
    • 4
    • 5
    • 6
    • 7
    • 8
    • 9
    • 10
    • 11
    • 12

    导入的包,如果出现错误进行参考

    import com.hb.model.Person;
    import com.mongodb.client.ListIndexesIterable;
    import com.mongodb.client.model.Indexes;
    import com.mongodb.client.result.DeleteResult;
    import com.mongodb.client.result.UpdateResult;
    import org.bson.Document;
    import org.junit.jupiter.api.Test;
    import org.springframework.boot.test.context.SpringBootTest;
    import org.springframework.data.domain.Sort;
    import org.springframework.data.mongodb.core.MongoTemplate;
    import org.springframework.data.mongodb.core.index.Index;
    import org.springframework.data.mongodb.core.index.IndexInfo;
    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 javax.annotation.Resource;
    import java.util.ArrayList;
    import java.util.List;
    @SpringBootTest
    class AppTests {
        @Resource
        private MongoTemplate mongoTemplate;
       
       }
    
    • 1
    • 2
    • 3
    • 4
    • 5
    • 6
    • 7
    • 8
    • 9
    • 10
    • 11
    • 12
    • 13
    • 14
    • 15
    • 16
    • 17
    • 18
    • 19
    • 20
    • 21
    • 22
    • 23
    • 24

    官方文档
    示例均以spring boot 测试类

    创建(增)

     //插入
        @Test
        //插入一条数据
        void mongoDBInsert() {
            Person shuai1 = Person.builder().id(1).name("小帅").girls(10086).build();
            mongoTemplate.insert(shuai1);
        }
        @Test
        //插入多条数据
        void mongoDBInsertAll() {
            List<Person> list = new ArrayList<>();
            for (int i = 0; i < 10; i++) {
                Person shuai1 = Person.builder().id(i).name("小帅"+ i).girls(10086).build();
                list.add(shuai1);
            }
            mongoTemplate.insertAll(list);
        }
    
    • 1
    • 2
    • 3
    • 4
    • 5
    • 6
    • 7
    • 8
    • 9
    • 10
    • 11
    • 12
    • 13
    • 14
    • 15
    • 16
    • 17

    修改(改)

     //更新
        @Test
        //有数据更新数据 没有数据创建数据
        void mongoDBSave() {
    
                Person shuai1 = Person.builder().id(1).name("小帅shuai ").girls(1008611).build();
            mongoTemplate.save(shuai1);
        }
        @Test
        //根据 条件 进行对多条数据进行更新
        void mongoDBUpdate() {
            Query query = new Query();
            query.addCriteria(Criteria.where("name").is("小帅"));
            Update update = new Update();
            Update id = update.set("name", "ggg");
            UpdateResult updateResult = mongoTemplate.updateMulti(query, update, Person.class);
            System.out.println(updateResult);
    
        }
        @Test
        //根据 条件 进行数据的更新
        void mongoDBUpset() {
            Query query = new Query();
            //更新的条件
            query.addCriteria(Criteria.where("id").is(3));
            //更新的内容
            Update update = new Update();
            Update id = update.set("name", "ggg");
            //更新找到的第一个数据
            UpdateResult updateResult = mongoTemplate.updateFirst(query, update, Person.class);
            System.out.println(updateResult);
        }
        @Test
        //根据 正则表达式 and 连接 条件 进行数据的更新
        void mongoDBUpsetMany() {
            Query query = new Query();
            Query query1 = query.addCriteria(Criteria.where("id").gt(4)
                    .and("name").regex(".*gg$"));
            Update update = new Update().set("name","嘎嘎");
            //更新找到的第一个数据
            UpdateResult updateResult = mongoTemplate.updateMulti(query,update,Person.class);
            System.out.println(updateResult);
        }
    
    • 1
    • 2
    • 3
    • 4
    • 5
    • 6
    • 7
    • 8
    • 9
    • 10
    • 11
    • 12
    • 13
    • 14
    • 15
    • 16
    • 17
    • 18
    • 19
    • 20
    • 21
    • 22
    • 23
    • 24
    • 25
    • 26
    • 27
    • 28
    • 29
    • 30
    • 31
    • 32
    • 33
    • 34
    • 35
    • 36
    • 37
    • 38
    • 39
    • 40
    • 41
    • 42
    • 43

    删除(删)

      //删
        @Test
        //根据 正则表达式 and 连接 条件 进行数据的删除 不返回数据
        void mongoDBDelete() {
            Query query = new Query();
            Query query1 = query.addCriteria(Criteria.where("id").gt(4)
                    .and("name").regex(".*嘎嘎$"));
            //更新找到的第一个数据
            DeleteResult remove = mongoTemplate.remove(query, Person.class);
            System.out.println(remove);
        }
        @Test
        //根据 正则表达式 and 连接 条件 进行数据的删除 返回数据
        void mongoDBDeleteReturnOne() {
            Query query = new Query();
            Query query1 = query.addCriteria(Criteria.where("id").lt(4)
                    .and("name").regex(".*gg$"));
            //更新找到的第一个数据
            Person andRemove = mongoTemplate.findAndRemove(query, Person.class);
            System.out.println(andRemove);
        }
        @Test
        //根据 正则表达式 and 连接 条件 进行数据的删除 返回数据
        void mongoDBDeleteReturnAny() {
            Query query = new Query();
            Query query1 = query.addCriteria(Criteria.where("id").lt(4)
                    .and("name").regex(".*gg$"));
            //更新找到的第一个数据
            List<Person> allAndRemove = mongoTemplate.findAllAndRemove(query, Person.class);
            System.out.println(allAndRemove);
       
        }
    
    
    • 1
    • 2
    • 3
    • 4
    • 5
    • 6
    • 7
    • 8
    • 9
    • 10
    • 11
    • 12
    • 13
    • 14
    • 15
    • 16
    • 17
    • 18
    • 19
    • 20
    • 21
    • 22
    • 23
    • 24
    • 25
    • 26
    • 27
    • 28
    • 29
    • 30
    • 31
    • 32
    • 33

    读取(查)

     //查
        @Test
            //找到全部
        void mongoDBFindAll() {
            List<Person> allAndRemove = mongoTemplate.findAll(Person.class);
            System.out.println(allAndRemove);
        }
        @Test
        //找到符合条件的第一个数据
        void mongoDBFindOne() {
            Query query = new Query();
            query.addCriteria(Criteria.where("id").in(1,2,3,4,5,6,7));
            //根据条件找到的第一个数据
            Person person= mongoTemplate.findOne(query,Person.class);
            System.out.println(person);
        }
        @Test
        //找到符合条件的第一个数据
        void mongoDBFindAny() {
            Query query = new Query();
            query.addCriteria(Criteria.where("id").in(1,2,3,4,5,6,7));
            //根据条件找到的第一个数据
            List<Person> people = mongoTemplate.find(query, Person.class);
            System.out.println(people
            );
        }
        @Test
        //找到id
        void mongoDBFindById() {
            //根据条件找到的第一个数据
            Person people = mongoTemplate.findById(3, Person.class);
            System.out.println(people);
        }
        @Test
        //找到 根据or和正则进行查找所有
        void mongoDBFindByOr() {
            Query query = new Query();
            query.addCriteria(Criteria.where("id").gte(4)
                    .orOperator(Criteria.where("name").regex("^小帅.*")));
            //根据条件找到的第一个数据
            List<Person> people = mongoTemplate.find(query, Person.class);
            System.out.println(people);
        }
        @Test
        //  find by sort
        // Sort.Direction.DESC 降序排列  默认为升序
        // 这里需要记得order by 在limit和skip之前
        void mongoDBFindBySort() {
            Query query = new Query();
            query.addCriteria(Criteria.where("id").gte(4)
                    .orOperator(Criteria.where("name").regex("^小帅.*")));
            query.with(Sort.by(Sort.Direction.DESC,"name")).limit(2).skip(3);
            //根据条件找到的第一个数据
            List<Person> people = mongoTemplate.find(query, Person.class);
            System.out.println(people);
        }
        @Test
        //  find by count
        void mongoDBCount() {
            Query query = new Query();
            query.addCriteria(Criteria.where("id").gte(4)
                    .orOperator(Criteria.where("name").regex("^小帅.*")));
            query.with(Sort.by(Sort.Direction.DESC,"name")).skip(3);
            //根据条件找到的第一个数据
            Long people = mongoTemplate.count(query, Person.class);
            System.out.println(people);
        }
    
    • 1
    • 2
    • 3
    • 4
    • 5
    • 6
    • 7
    • 8
    • 9
    • 10
    • 11
    • 12
    • 13
    • 14
    • 15
    • 16
    • 17
    • 18
    • 19
    • 20
    • 21
    • 22
    • 23
    • 24
    • 25
    • 26
    • 27
    • 28
    • 29
    • 30
    • 31
    • 32
    • 33
    • 34
    • 35
    • 36
    • 37
    • 38
    • 39
    • 40
    • 41
    • 42
    • 43
    • 44
    • 45
    • 46
    • 47
    • 48
    • 49
    • 50
    • 51
    • 52
    • 53
    • 54
    • 55
    • 56
    • 57
    • 58
    • 59
    • 60
    • 61
    • 62
    • 63
    • 64
    • 65
    • 66
    • 67

    创建索引

        //索引操作
    
        @Test
        public void createAscendingIndex() {
            // 设置字段名称
            String field = "age";
            // 通过表名字创建索引
            mongoTemplate.getCollection("person").createIndex(Indexes.descending(field));
            //获取索引位置 Person.class 对应的 ”206_Person“
            int i = mongoTemplate.getCollectionName(Person.class).indexOf("age");
            System.out.println(i);
    
            //设置 Person对应的 206_persion 中的索引
            String s = mongoTemplate.indexOps(Person.class).ensureIndex(new Index().on("id", Sort.Direction.ASC));
            System.out.println(s);
        }
    
        /**
         * 根据索引名称移除索引
         */
        @Test
        public void removeIndex() {
            // 设置字段名称
            String field = "age_-1";
            // 删除索引
            mongoTemplate.getCollection("person").dropIndex(field);
           // mongoTemplate.indexOps(Person.class).dropIndex(field);
        }
    
        /**
         * 查询集合中所有的索引
         */
        @Test
        public void getIndexAll() {
            // 获取集合中所有列表 by 表名字
            ListIndexesIterable<Document> indexes = mongoTemplate.getCollection("person").listIndexes();
            // 获取索引
            for (Document index : indexes) {
                System.out.println(index.toJson());
                System.out.println("-----------------------------");
            }
            // 获取集合中所有列表 by 类
            List<IndexInfo> indexInfo = mongoTemplate.indexOps(Person.class).getIndexInfo();
            for (IndexInfo info : indexInfo) {
                System.out.println("206 " + info);
            }
        }
    
    • 1
    • 2
    • 3
    • 4
    • 5
    • 6
    • 7
    • 8
    • 9
    • 10
    • 11
    • 12
    • 13
    • 14
    • 15
    • 16
    • 17
    • 18
    • 19
    • 20
    • 21
    • 22
    • 23
    • 24
    • 25
    • 26
    • 27
    • 28
    • 29
    • 30
    • 31
    • 32
    • 33
    • 34
    • 35
    • 36
    • 37
    • 38
    • 39
    • 40
    • 41
    • 42
    • 43
    • 44
    • 45
    • 46
    • 47
  • 相关阅读:
    基于php+MYSQL的旅游景点攻略的设计与实现毕业设计源码301216
    C++智能指针之weak_ptr
    Standard part function
    springboot+java+vue毕业生学习交流平台g1el1
    PHP – 最佳实践
    cache line提升程序性能
    【史上最简单】idea 打开 eclipse 项目
    JavaScript小技能:对象
    二、VXLAN BGP EVPN基本原理
    Effective C++ 规则39:明智而谨慎的使用private继承
  • 原文地址:https://blog.csdn.net/weixin_63558979/article/details/132910139