# MongoDB

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

#### pom.xml

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

#### User 객체 작성

```java
@Data
public class User {

    @Id
    private Long id;

    private String username;
    private Integer age;

}
```

#### Repository interface 작성

```java
public interface UserRepository extends MongoRepository<User, Long> {

    User findByUsername(String username);

}
```

#### 테스트 코드 작성

```java
@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
```

{% hint style="info" %}
mongodb 2.x  아래와 같이 지정할수 있음. 단 mongodb 3.x 안됨.\
spring.data.mongodb.host=localhost spring.data.mongodb.port=27017
{% endhint %}


---

# Agent Instructions: Querying This Documentation

If you need additional information that is not directly available in this page, you can query the documentation dynamically by asking a question.

Perform an HTTP GET request on the current page URL with the `ask` query parameter:

```
GET https://blakes-organization.gitbook.io/rainsister/springboot-2.x/database/mongodb.md?ask=<question>
```

The question should be specific, self-contained, and written in natural language.
The response will contain a direct answer to the question and relevant excerpts and sources from the documentation.

Use this mechanism when the answer is not explicitly present in the current page, you need clarification or additional context, or you want to retrieve related documentation sections.
