MongoDB

1.Docker安装MongoDB

拉取镜像

docker pull mongo

创建容器

docker run -di --name mongo-service --restart=always \
-p 27017:27017 -v ~/data/mongodata:/data \
-e MONGO_INITDB_ROOT_USERNAME=用户名 \
-e MONGO_INITDB_ROOT_PASSWORD=密码 \
mongo

查看所有容器

docker ps

使用Navicat连接MongoDB

2.SpringBoot集成MongoDB

(1).配置

1.mongoDB依赖

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

2.mongoDB的yaml配置

spring:
  data:
    mongodb:
      host: ip地址
      port: 27017
      username: 用户名
      password: 密码
      database: 连接的数据库名称
      authentication-database: admin

3.映射

/**
 * <p>
 * 联想词表
 * </p>
 *
 * @author Qeem
 */
@Data
@Document("ap_associate_words")  //集合(可有可无,没有的时候保存会自动创建)
public class ApAssociateWords implements Serializable {

    private static final long serialVersionUID = 1L;

    private String id;

    /**
     * 联想词
     */
    private String associateWords;

    /**
     * 创建时间
     */
    private Date createdTime;

}

(2).测试

1.保存

@Autowired
    private MongoTemplate mongoTemplate;

    //保存
    @Test
    public void saveTest(){
        ApAssociateWords apAssociateWords = new ApAssociateWords();
        apAssociateWords.setAssociateWords("Qeem简直是个天才!");
        apAssociateWords.setCreatedTime(new Date());
        mongoTemplate.save(apAssociateWords);
    }

2.查询

 @Autowired
    private MongoTemplate mongoTemplate;

    //查询一个
    @Test
    public void saveFindOne(){
        ApAssociateWords apAssociateWords = mongoTemplate.findById("64c0c36debb526728b49e856", ApAssociateWords.class);
        System.out.println(apAssociateWords);
    }

3.条件查询

@Autowired
    private MongoTemplate mongoTemplate;


    //条件查询(associateWords字段=='Qeem简直是个天才!')
    @Test
    public void testQuery(){
        Query query = Query.query(Criteria.where("associateWords").is("Qeem简直是个天才!"))
                .with(Sort.by(Sort.Direction.DESC,"createdTime"));
        List<ApAssociateWords> apAssociateWordsList = mongoTemplate.find(query, ApAssociateWords.class);
        System.out.println(apAssociateWordsList);
    }

4.删除

  @Autowired
    private MongoTemplate mongoTemplate;

    //删除(associateWords字段=='Qeem简直是个天才!')
    @Test
    public void testDel(){
        mongoTemplate.remove(Query.query(Criteria.where("associateWords").is("Qeem简直是个天才!")),ApAssociateWords.class);
    }

end
SpringBoot
MongoDB
Java
Linux
Docker

评论区

暂无评论