DB

RESTHeart CRUD(Create, Read, Update, Delete)

ipxy 2025. 4. 15. 09:55
728x90

📂 데이터베이스 및 컬렉션 생성

1. 데이터베이스 생성

  • Method: PUT
  • URL: http://localhost:8080/mydb

이 요청은 mydb라는 이름의 데이터베이스를 생성합니다.

2. 컬렉션 생성

  • Method: PUT
  • URL: http://localhost:8080/mydb/mycollection

이 요청은 mydb 데이터베이스 내에 mycollection이라는 컬렉션을 생성합니다.


📝 문서 작업

3. 문서 생성 (Create)

  • Method: POST
  • URL: http://localhost:8080/mydb/mycollection
  • Headers:
    • Content-Type: application/json
  • Body (raw JSON):
{ "item": "notebook", "qty": 50, "size": { "h": 8.5, "w": 11, "uom": "in" }, "status": "A" }

이 요청은 mycollection 컬렉션에 새로운 문서를 추가합니다.

4. 문서 조회 (Read)

a. 전체 문서 조회

  • Method: GET
  • URL: http://localhost:8080/mydb/mycollection

컬렉션 내의 모든 문서를 조회합니다.

b. 특정 문서 조회

  • Method: GET
  • URL: http://localhost:8080/mydb/mycollection/{document_id}

{document_id}는 조회하려는 문서의 _id 값입니다.

c. 필터를 사용한 조회

  • Method: GET
  • URL: http://localhost:8080/mydb/mycollection?filter={"status":"A"}

status 필드가 "A"인 문서만 조회합니다.

d. 페이징 처리

  • Method: GET
  • URL: http://localhost:8080/mydb/mycollection?pagesize=10&page=2

한 페이지에 10개의 문서를 표시하며, 두 번째 페이지를 조회합니다.

5. 문서 수정 (Update)

a. 전체 문서 교체

  • Method: PUT
  • URL: http://localhost:8080/mydb/mycollection/{document_id}
  • Headers:
    • Content-Type: application/json
  • Body (raw JSON):
{ "item": "notebook", "qty": 60, "size": { "h": 8.5, "w": 11, "uom": "in" }, "status": "B" }

문서의 전체 내용을 새로운 데이터로 교체합니다.

b. 부분 수정

  • Method: PATCH
  • URL: http://localhost:8080/mydb/mycollection/{document_id}
  • Headers:
    • Content-Type: application/json
  • Body (raw JSON)
{ "qty": 70 }

문서의 qty 필드만 70으로 수정합니다.

6. 문서 삭제 (Delete)

  • Method: DELETE
  • URL: http://localhost:8080/mydb/mycollection/{document_id}

지정한 문서를 삭제합니다.


🔍 다양한 조회 방법

1. 특정 필드 값으로 필터링

  • URL: /inventory?filter={"status":"A"}
  • 설명: status 필드가 "A"인 문서를 조회합니다.

2. 비교 연산자 사용

  • URL: /inventory?filter={"qty":{"$gt":30}}
  • 설명: qty 필드가 30보다 큰 문서를 조회합니다.

3. 논리 연산자 사용

  • URL: /inventory?filter={"$or":[{"status":"A"},{"qty":{"$lt":50}}]}
  • 설명: status가 "A"이거나 qty가 50보다 작은 문서를 조회합니다.

4. 특정 필드만 선택 (Projection)

  • URL: /inventory?keys={"item":1,"qty":1}
  • 설명: item과 qty 필드만 포함하여 문서를 조회합니다.

5. 정렬

  • URL: /inventory?sort={"qty":-1}
  • 설명: qty 필드를 기준으로 내림차순 정렬하여 문서를 조회합니다.

6. 페이징

  • URL: /inventory?page=2&pagesize=5
  • 설명: 두 번째 페이지의 5개 문서를 조회합니다.

7. 배열 필드에서 특정 값 포함 여부

  • URL: /inventory?filter={"foods":{"$in":["yogurt"]}}
  • 설명: foods 배열에 "yogurt"가 포함된 문서를 조회합니다.

8. 텍스트 검색

  • 사전 작업: 텍스트 인덱스를 생성해야 합니다.
    • Method: PUT
    • URL: /inventory/_indexes/textIndex
    • Body (JSON):
    • { "keys": { "item": "text" } }
  • 검색 예제:
    • URL: /inventory?filter={"$text":{"$search":"notebook"}}
    • 설명: item 필드에서 "notebook"이라는 단어를 포함하는 문서를 조회합니다.
{
  "keys": { "item": "text" }
}
728x90