MongoDB

공식 사이트 https://www.mongodb.org/

pom.xml

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

User 객체 작성

@Data
public class User {

    @Id
    private Long id;

    private String username;
    private Integer age;

}

Repository interface 작성

public interface UserRepository extends MongoRepository<User, Long> {

    User findByUsername(String username);

}

테스트 코드 작성

@SpringBootTest(classes = MongoDBApplication.class)
public class ApplicationTests {

    @Autowired
    private UserRepository userRepository;

    @Test
    public void test() throws Exception {
        userRepository.deleteAll();

        userRepository.save(new User(1L, "didi", 30));
        userRepository.save(new User(2L, "mama", 40));
        userRepository.save(new User(3L, "kaka", 50));
        Assertions.assertEquals(3, userRepository.findAll().size());

        User u = userRepository.findById(1L).get();
        userRepository.delete(u);
        Assertions.assertEquals(2, userRepository.findAll().size());

        u = userRepository.findByUsername("mama");
        userRepository.delete(u);
        Assertions.assertEquals(1, userRepository.findAll().size());
    }

}

application.properties

spring.data.mongodb.uri=mongodb://name:pass@localhost:27017/test

mongodb 2.x 아래와 같이 지정할수 있음. 단 mongodb 3.x 안됨. spring.data.mongodb.host=localhost spring.data.mongodb.port=27017

Last updated