MongoDB 安装和使用(增删改查,设置索引)

1.1 基于Docker安装

docker run --restart=always -d --name mongo -v 
/opt/mongodb/data:/data/db -p 27017:27017 
registry.cn-beijing.aliyuncs.com/all100/mongo:4.0.6

1.2 客户端工具使用

客户端下载

MongoDB Compass | MongoDB

2.MongoDB 使用

2.1 引用依赖包

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

2.2 配置文件配置mongodb资料

# MongoDB连接信息
spring.data.mongodb.host = 192.168.23.27
spring.data.mongodb.port = 27017
spring.data.mongodb.database = mall#用于控制MongoDB数据库是否自动创建索引。spring.data.mongodb.auto-index-creation = true

2.3 准备对象Person

@Document(collection = "person") // 指定集合名称,就是类似mysql的表,如果不指定就以类名称作为集合名称
@Data
public class Person {
    @Id // 文档id, 很重要,类似mysql表的主键
    private Integer id;
    private String name;
    private Integer age;
    /**
     * 创建一个10秒之后文档自动删除的索引 结合 spring.data.mongodb.auto-index-creation = true 一起使用       创建一个10秒之后文档自动删除, 类似 redis ttl注意:这个字段必须是date类型或者是一个包含date类型值的数组字段,一般我们使用date类型;
     */
    @Indexed(expireAfterSeconds=10)
    private LocalDateTime createTime;
}

TTL:

@Indexed(expireAfterSeconds=10) 是 MongoDB 的 Java 驱动程序中用于设置 TTL (Time To Live) 索引的一种注解方式。TTL 索引是一种特殊的索引类型,用于自动删除满足条件的文档。当文档中的某个字段的值超过了设定的时间间隔,MongoDB 会自动删除这些文档。

日期类型:

MongoDB 中的日期类型 (Date) 默认是以 协调世界时(UTC) 存储的。这意味着无论你在哪个时区插入或查询日期,MongoDB 始终使用 UTC 格式来表示日期和时间戳。当你向 MongoDB 插入一个日期值时,该值会被转换为 UTC 格式。同样地,当你从 MongoDB 中读取日期值时,返回的值也是 UTC 格式的。例如,如果你插入了一个 new Date() 对象,MongoDB 会将其转换为 UTC 格式进行存储。

清理机制:

MongoDB 的后台任务通常每 60 秒执行一次,但实际执行频率可能会因系统负载和其他因素而有所不同。这意味着即使一个文档已经超过了 10 秒的过期时间,它可能仍然存在一段时间,直到后台任务运行并清理过期文档为止。

-v /etc/localtime:/etc/localtime 解决时区问题

3.1 新增文档


    @Autowired
    private MongoTemplate mongoTemplate;

    /**
     * 插入文档
     */
    @Test
    void insert() {
        Person person =new Person();
        person.setId(20530712L);
        person.setName("张三");
        person.setAge(26);
        mongoTemplate.insert(person);

    }
    /**
     * 自定义集合,插入文档
     */
    @Test
    public void insertCustomCollection() throws Exception {
        Person person =new Person();
        person.setId(20530712L);
        person.setName("张三");
        person.setAge(26);
        person.setCreateTime(LocalDateTimeUtil.now());
        mongoTemplate.insert(person, "custom_person");
    }
    /**
     * 批量插入文档
     */
    @Test
    public void insertBatch() throws Exception {
        List<Person> personList = new ArrayList<>();
        for (int i = 1; i < 5; i++) {
            Person person =new Person();
            person.setId(i);
            person.setName("张三"+i);
            person.setAge(26);
            person.setCreateTime(LocalDateTimeUtil.now());
            personList.add(person);

        }

       //mongoTemplate.insert(personList, "custom_person");
        mongoTemplate.insertAll(personList);
    }
    /**
     * 存储文档,如果没有插入,否则更新
     * 在存储文档的时候会通过主键 ID 进行判断,如果存在就更新,否则就插入
     */
    @Test
    public void save() throws Exception {
        Person person =new Person();
        person.setId(1L);
        person.setName("张三33");
        person.setAge(26);
        person.setCreateTime(LocalDateTimeUtil.now());
        mongoTemplate.save(person);
    }

3.2 修改文档

    @Autowired
    private MongoTemplate mongoTemplate;

    /**
     * 更新文档,匹配查询到的文档数据中的第一条数据
     * @throws Exception
     */
    @Test
    public void update1() throws Exception {
     
        //更新条件
        Query query= new Query(Criteria.where("id").is(2));
        //更新值
        Update update= new Update().set("name", person.getName()).set("age", 32);
        //更新查询满足条件的文档数据(第一条)
        UpdateResult result =mongoTemplate.updateFirst(query, update, Person.class);
        System.out.println("更新条数:" + result.getMatchedCount());
    }
    /**
     * 更新文档,匹配查询到的文档数据中的所有数据
     */
    @Test
    public void updateMany() throws Exception {

        //更新年龄大于等于32的人
        Query query= new Query(Criteria.where("age").gte(18));
        //更新姓名为 “我成人了”
        Update update= new Update().set("name", "我成人了");
        //更新查询满足条件的文档数据(全部)
        UpdateResult result = mongoTemplate.updateMulti(query, update, Person.class);
        System.out.println("更新条数:" + result.getMatchedCount());
    }


3.3 删除文档

     @Autowired
    private MongoTemplate mongoTemplate;

    /**
     * 删除符合条件的所有文档
     */
    @Test
    public void remove() throws Exception {
      //删除年龄小于18的所有人
        Query query = new Query(Criteria.where("age").lt(18));
        DeleteResult result = mongoTemplate.remove(query, Person.class);
        System.out.println("删除条数:" + result.getDeletedCount());
    }

    /**
     * 删除符合条件的单个文档,并返回删除的文档
     */
    @Test
    public void findAndRemove() throws Exception {

        Query query = new Query(Criteria.where("id").is(1L));
        Person result = mongoTemplate.findAndRemove(query, Person.class);
        System.out.println("删除的文档数据:" + result);
    }

    /**
     * 删除符合条件的所有文档,并返回删除的文档
     */
    @Test
    public void findAllAndRemove() throws Exception {

        // 使用 in 删除 符合条件的多条文档,并返回
        Query query = new Query(Criteria.where("id").in(1,2,3));
        List<Person> result = mongoTemplate.findAllAndRemove(query, Person.class);
        System.out.println("删除的文档数据:" + result.toString());
    }



3.4 查询文档

1.原生查询

// 查询姓名 以 “张” 开始的数据db.getCollection("my_person").find({ name: /^张/ })// 姓名 以 “大”  结尾的数据db.getCollection("my_person").find({ name: /大$/})
// 满足 以 “张”开始,同时 age 小于等于12   类似用 and 

db.getCollection("my_person").find({ name: /^张/, age:{$lte:12}})

2.Java实现

     @Autowired
    private MongoTemplate mongoTemplate;

    /**
     * 查询集合中的全部文档数据
     */
    @Test
    public void findAll()  {
        List<Person> result = mongoTemplate.findAll(Person.class);
        System.out.println("查询结果:" + result.toString());
    }

    /**
     * 查询集合中指定的ID文档数据
     */
    @Test
    public void findById() {
        long id = 2;
        Person result = mongoTemplate.findById(id, Person.class);
        System.out.println("查询结果:" + result.toString());
    }
    /**
     * 根据条件查询集合中符合条件的文档,返回第一条数据
     */
    @Test
    public void findOne() {
        Query query = new Query(Criteria.where("name").is("张三3"));
        Person result = mongoTemplate.findOne(query, Person.class);
        System.out.println("查询结果:" + result.toString());
    }

    /**
     * 根据条件查询所有符合条件的文档
     */
    @Test
    public void findByCondition() {

        Query query = new Query(Criteria.where("age").gt(18));
        List<Person> result = mongoTemplate.find(query, Person.class);
        System.out.println("查询结果:" + result.toString());
    }
    /**
     * 根据【AND】关联多个查询条件,查询集合中所有符合条件的文档数据
     */
    @Test
    public void findByAndCondition() {
        // 创建条件
        Criteria name = Criteria.where("name").is("张三");
        Criteria age = Criteria.where("age").is(18);
        // 创建条件对象,将上面条件进行 AND 关联    where  name='张三' and age = 18
        Criteria criteria = new Criteria().andOperator(name, age);
        // 创建查询对象,然后将条件对象添加到其中
        Query query = new Query(criteria);
        List<Person> result = mongoTemplate.find(query, Person.class);
        System.out.println("查询结果:" + result.toString());
    }
    /**
     * 根据【OR】关联多个查询条件,查询集合中的文档数据
     */
    @Test
    public void findByOrCondition() {
        // 创建条件
        Criteria criteriaUserName = Criteria.where("name").is("张三");
        Criteria criteriaPassWord = Criteria.where("age").is(22);
        // 创建条件对象,将上面条件进行 OR 关联  where  name='张三' or age = 22
        Criteria criteria = new Criteria().orOperator(criteriaUserName, criteriaPassWord);
        // 创建查询对象,然后将条件对象添加到其中
        Query query = new Query(criteria);
        List<Person> result = mongoTemplate.find(query, Person.class);
        System.out.println("查询结果:" + result.toString());
    }
    /**
     * 根据【IN】关联多个查询条件,查询集合中的文档数据
     */
    @Test
    public void findByInCondition() {
        // 设置查询条件参数
        List<Long> ids = Arrays.asList(10L, 11L, 12L);
        // 创建条件
        Criteria criteria = Criteria.where("id").in(ids);
        // 创建查询对象,然后将条件对象添加到其中
        Query query = new Query(criteria);
        List<Person> result = mongoTemplate.find(query, Person.class);
        System.out.println("查询结果:" + result.toString());
    }

    /**
     * 根据【逻辑运算符】查询集合中的文档数据
     */
    @Test
    public void findByOperator() {
        // 设置查询条件参数
        int min = 20;
        int max = 35;
        Criteria criteria = Criteria.where("age").gt(min).lte(max);
        // 创建查询对象,然后将条件对象添加到其中
        Query query = new Query(criteria);
        List<Person> result = mongoTemplate.find(query, Person.class);
        System.out.println("查询结果:" + result.toString());
    }
    /**
     * 根据【正则表达式】查询集合中的文档数据
     */
    @Test
    public void findByRegex() {
        // 设置查询条件参数
        String regex = "^张";
        Criteria criteria = Criteria.where("name").regex(regex);
        // 创建查询对象,然后将条件对象添加到其中
        Query query = new Query(criteria);
        List<Person> result = mongoTemplate.find(query, Person.class);
        System.out.println("查询结果:" + result.toString());
    }

    /**
     * 根据条件查询集合中符合条件的文档,获取其文档列表并排序
     */
    @Test
    public void findByConditionAndSort() {
        Query query = new Query(Criteria.where("name").is("张三")).with(Sort.by("age"));
        List<Person> result = mongoTemplate.find(query, Person.class);
        System.out.println("查询结果:" + result.toString());
    }

    /**
     * 根据单个条件查询集合中的文档数据,并按指定字段进行排序与限制指定数目
     */
    @Test
    public void findByConditionAndSortLimit() {
        String userName = "张三";
        //从第5行开始,查询3条数据返回
        Query query = new Query(Criteria.where("name").is("张三"))
                .with(Sort.by("createTime"))
                .limit(3).skip(5);
        List<Person> result = mongoTemplate.find(query, Person.class);
        System.out.println("查询结果:" + result.toString());
    }
    /**
     * 统计集合中符合【查询条件】的文档【数量】
     */
    @Test
    public void countNumber() {
        // 设置查询条件参数
        String regex = "^张*";
        Criteria criteria = Criteria.where("name").regex(regex);
        // 创建查询对象,然后将条件对象添加到其中
        Query query = new Query(criteria);
        long count = mongoTemplate.count(query, Person.class);
        System.out.println("统计结果:" + count);
    }


3.4 创建索引

        @Autowired
    private MongoTemplate mongoTemplate;

    /**
     * 创建升序索引
     */
    @Test
    public void createAscendingIndex() {
        // 设置字段名称
        String field = "age";
        // 创建索引
        mongoTemplate.getCollection("person").createIndex(Indexes.descending(field));
    }

    /**
     * 根据索引名称移除索引
     */
    @Test
    public void removeIndex() {
        // 设置字段名称
        String field = "age_1";
        // 删除索引
        mongoTemplate.getCollection("person").dropIndex(field);
    }


    /**
     * 查询集合中所有的索引
     */
    @Test
    public void getIndexAll() {
        // 获取集合中所有列表
        ListIndexesIterable<Document> indexList =   mongoTemplate.getCollection("person").listIndexes();
        // 获取集合中全部索引信息
        for (Document document : indexList) {
            System.out.println("索引列表:" + document);
        }
    }

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

打赏作者

这孩子叫逆

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

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

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

打赏作者

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

抵扣说明:

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

余额充值