Mac环境下安装MongoDB环境

教程

https://docs.mongodb.com/manual/tutorial/install-mongodb-on-os-x/

下载

https://www.mongodb.com/download-center/community?jmp=docs

案例下载地址:https://fastdl.mongodb.org/osx/mongodb-osx-ssl-x86_64-4.0.6.tgz

配置

./bin/mongod --dbpath /Users/kevin/software/mongodb-osx-x86_64-4.0.6/data --logpath /Users/kevin/software/mongodb-osx-x86_64-4.0.6/log/mongo.log --noauth --logappend --fork --port 27017 &

启动

停止

测试

进入客户端

use test

db.student.insert({"sid":"S2012211598","name":"cat","age":25})

Springboot测试

  1. 新建SpringBoot工程
  2. 添加maven依赖
 <dependency>
    <groupId>org.springframework.boot</groupId>
    <artifactId>spring-boot-starter-data-mongodb</artifactId>
</dependency>
<dependency>
    <groupId>org.springframework.boot</groupId>
    <artifactId>spring-boot-starter-test</artifactId>
    <scope>test</scope>
</dependency>
  1. application.properties
spring.data.mongodb.host=localhost
spring.data.mongodb.password=
spring.data.mongodb.port=27017
spring.data.mongodb.database=test
spring.data.mongodb.repositories.type=auto
  1. 添加EnableMongoRepositories注解
@SpringBootApplication
@EnableMongoRepositories(basePackages = "morning.cat.springdatademo.mongo.repository")
public class SpringdataDemoApplication {
    public static void main(String[] args) {
        SpringApplication.run(SpringdataDemoApplication.class, args);
    }
}
  1. 定义实体类
import lombok.Data;
import lombok.experimental.Accessors;
import javax.persistence.Table;
@Table
@Data
@Accessors(chain = true)
public class Student {
    private String sid;
    private String name;
    private Integer age;
}
  1. 继承MongoRepository
public interface StudentRepository extends MongoRepository<Student, Long> {
    Student findBySid(String code);
}
  1. 测试类
import org.junit.Test;
import org.junit.runner.RunWith;
import org.springframework.boot.test.context.SpringBootTest;
import org.springframework.test.context.junit4.SpringRunner;

@RunWith(SpringRunner.class)
@SpringBootTest
public class BaseTests {

    @Autowired
    private StudentRepository studentRepository;

    @Test
    public void contextLoads() {
        studentRepository.insert(new Student().setSid("S2018234234").setName("gouzi").setAge(22));
    }

}
  1. 使用MongoChef客户端查看数据
02-21 16:34