MongoDB-Springboot 入门

一、MongoDB简介

  • MongoDB是一个由C++编写的,基于分布式文件存储的开源数据库系统。

  • 通过添加节点可以快速扩容,保证服务器性能。

  • 存储结构由键值(key, value)对组成。类似于 json 对象。

    1
    2
    3
    4
    5
    6
    {
    name: "jim",
    age: 25,
    status: "A",
    groups: ["news", "sports"]
    }

二、基本概念

Mongo是一个NoSQL 的文档数据库,可以对比 SQL 中的一些概念来理解。

SQL术语/概念 MongoDB术语/概念 解释/说明
database database 数据库
table collection 数据库表/集合
row document 数据记录行/文档
column field 数据字段/域
index index 索引
table joins lookup 表关联
primary key primary key 主键,MongoDB自动将_id字段设置为主键

三、基础操作-增删改查

1、新增

db.collection.insertOne()
db.collection.insertMany()
db.collection.insert()

2、修改

db.collection.updateOne()

db.collection.updateMany()

db.collection.replaceOne()

db.collection.update()

db.person.update({name: ‘张三’}, {$set: {age: 30}}, {multi: true})

db.person.update({name: ‘张三’}, {$set: {‘address.$[i].no’: 50}}, {arrayFilters: [{‘i.province’: ‘上海’}]})

update person set age = 30 where name = ‘张三’;

3、删除

db.collection.deleteOne()

db.collection.deleteMany()

db.collection.remove()

4、查询

  • find

db.collection.find()

  • aggregate

db.collection.aggregate

Springboot-mongo

1、引入依赖

1
2
3
4
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-data-mongodb</artifactId>
</dependency>

2、配置mongo客户端

1
2
3
4
5
6
7
spring.data.mongodb.uri=mongodb://MEDBUser:MEDBUser@172.172.172.172:20000,172.172.172.173:20000,172.172.172.174:20000/MedicalExaminationDB4
# 或者以下
spring.data.mongodb.host=mongoserver.example.com
spring.data.mongodb.port=27017
spring.data.mongodb.database=test
spring.data.mongodb.username=user
spring.data.mongodb.password=secret

3、配置连接池(两种方式都可以,第二种有优先级更高)

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
package com.joking.springbootmongo.config;

import com.mongodb.MongoClientSettings;
import org.bson.codecs.configuration.CodecRegistry;
import org.bson.codecs.pojo.PojoCodecProvider;
import org.springframework.boot.autoconfigure.mongo.MongoClientSettingsBuilderCustomizer;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import org.springframework.data.mongodb.core.MongoClientSettingsFactoryBean;

import java.util.concurrent.TimeUnit;

import static org.bson.codecs.configuration.CodecRegistries.fromProviders;
import static org.bson.codecs.configuration.CodecRegistries.fromRegistries;

@Configuration
public class MongoConfig {

@Bean
public MongoClientSettingsFactoryBean mongoClientSettingsFactoryBean() {
MongoClientSettingsFactoryBean factoryBean = new MongoClientSettingsFactoryBean();
factoryBean.setPoolMaxConnectionIdleTimeMS(5000);
factoryBean.setPoolMaxSize(100);
factoryBean.setPoolMinSize(10);
return factoryBean;
}

@Bean
public MongoClientSettingsBuilderCustomizer mongoClientSettingsBuilderCustomizer() {
MongoClientSettingsBuilderCustomizer builder = clientSettingsBuilder -> {
clientSettingsBuilder.applyToConnectionPoolSettings(settings -> {
settings.maxConnectionIdleTime(1000, TimeUnit.SECONDS);
settings.maxSize(100);
settings.minSize(3);
});
clientSettingsBuilder.codecRegistry(this.codecRegistry());
};
return builder;
}

public CodecRegistry codecRegistry() {
return fromRegistries(MongoClientSettings.getDefaultCodecRegistry(),
fromProviders(PojoCodecProvider.builder().automatic(true).build()));
}
}

4、测试

  • entity

    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
    package com.joking.springbootmongo.entity;

    import lombok.AllArgsConstructor;
    import lombok.Data;
    import lombok.NoArgsConstructor;
    import lombok.ToString;

    import java.util.List;

    @Data
    @ToString
    @NoArgsConstructor
    @AllArgsConstructor
    public class Person {
    private String name;
    private int age;
    private List<Address> address;


    @Data
    @ToString
    @AllArgsConstructor
    public static class Address {
    private String province;
    private String city;
    private String street;
    private int no;

    }
    }
  • repository

    1
    2
    3
    4
    5
    6
    7
    8
    9
    10
    11
    12
    13
    14
    15
    16
    17
    18
    19
    package com.joking.springbootmongo.repository;

    import com.joking.springbootmongo.entity.Person;
    import org.bson.types.ObjectId;
    import org.springframework.data.mongodb.repository.MongoRepository;
    import org.springframework.stereotype.Repository;

    import java.util.List;
    import java.util.Optional;

    @Repository
    public interface PersonRepository extends MongoRepository<Person, ObjectId> {

    Optional<List<Person>> findByName(String name);

    Optional<List<Person>> findByAddressProvince(String name);

    Optional<List<Person>> findByNameRegex(String name);
    }
  • JunitTest

    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
    package com.joking.springbootmongo.repository;

    import com.joking.springbootmongo.entity.Person;
    import lombok.extern.slf4j.Slf4j;
    import org.junit.jupiter.api.Test;
    import org.springframework.beans.factory.annotation.Autowired;
    import org.springframework.boot.test.context.SpringBootTest;
    import org.springframework.data.mongodb.core.MongoTemplate;

    import static java.util.Arrays.asList;

    @Slf4j
    @SpringBootTest
    public class PersonRepositoryTest {

    @Autowired
    private PersonRepository personRepository;

    @Autowired
    private MongoTemplate mongoTemplate;

    @Test
    public void testSave() {
    Person person = new Person();
    person.setName("张三");
    person.setAge(10);
    person.setAddress(
    asList(
    new Person.Address("北京", "海淀", "建外", 10)
    )
    );
    Person save = personRepository.save(person);
    log.info(save.toString());
    }

    @Test
    public void findByNameTest() {
    personRepository.findByName("张三")
    .ifPresent(i -> {
    i.forEach(j -> log.info(j.toString()));
    });
    }

    @Test
    public void findByAddressProvinceTest() {
    personRepository.findByAddressProvince("北京")
    .ifPresent(i -> {
    i.forEach(j -> log.info(j.toString()));
    });
    }

    @Test
    public void findByNameRegexTest() {
    personRepository.findByNameRegex("三")
    .ifPresent(i -> {
    i.forEach(j -> log.info(j.toString()));
    });
    }



    }

 评论



本站由Hexo强力驱动 🔥 使用 Material-x 作为主题

总访问量为 次 。