ABOUT ME

-

Today
-
Yesterday
-
Total
-
  • MongoDB 쿼리로 CRUD 해보기
    프로젝트/mongoDB 2024. 2. 4. 00:01
    728x90

    개요

    MongoDB CRUD Operations 공식문서를 기반으로 MongoDB CRUD를 수행해보고자 합니다.

    특별한 설치 없이 수행할 수 있는 mongoplayground를 활용해보겠습니다.

     

    CRUD란?

    Create, Read, Update, Delete의 약어로 문서에 대한 생성, 읽기, 갱신, 삭제를 의미합니다.

     

     

    Create Operation

    users라는 collection에 user의 정보인 document를 저장

    collection에 새로운 document를 생성하거나 삽입할 수 있는 명령어입니다.

    만약 collection이 존재하지 않는다면 collection이 생성됩니다.

    아쉽게도 playgroud에서는 create operation은 지원하지 않습니다.

    insertOne 문법

    db.collection.insertOne(
        <document>,
        {
          writeConcern: <document>
        }
    )

    1개의 문서를 insert 하는 구문입니다.

     

    insertMany 문법

    db.collection.insertMany(
       [ <document 1> , <document 2>, ... ],
       {
          writeConcern: <document>,
          ordered: <boolean>
       }
    )

    N개의 문서를 insert하는 구문입니다.

     

     

    writeConcern 옵션

    2개의 문법에서 공통적으로 등장하는 writeConcern 옵션은 primary와 secondary DB들의 정합성을 맞출 수 있도록 지원해 주는 옵션입니다.

     

    ordered 옵션

    ordered 옵션은 병렬성에 관한 옵션입니다.

    기본적으로 true이며 싱글스레드로 순차적으로 처리합니다.

    반면에 해당 설정은 false로 주면 멀티스레드로 처리합니다.

     

    성능적으로 멀티스레드가 더 좋은 거 아닐까?라는 생각이 들 수 있습니다.

    하지만 싱글스레드에서 1 -> 2 -> 3 -> 4를 수행하면서 2에서 오류가 발생했을 때 3, 4는 작업이 안되지만 멀테스레드에서 동일한 상황이 발생하면 1,3,4는 작업이 되고 2에서는 오류가 발생해서 작업이 되지 않습니다.

     

    따라서 상황에 따라 적절하게 고려해야 합니다.

     

     

    Read Operation

    collection에서 문서를 검색하는 과정입니다.

    read를 수행할 때 여러 조건(query criteria, projection, cursor modifier)을 줄 수 있습니다.

     

    playground에서 find 명령어 실습

    db.collection.find() 문법을 활용하여 colletion 내의 문서를 검색할 수 있습니다.

     

    // SQL 문법
    SELECT * FROM collection WHERE status = "sleep"
    
    // mongoDB 문법
    db.collection.find({
      status: "sleep"
    })

    특정 조건에 해당하는 document만 쿼리 하는 방법입니다.

    SQL에서 사용하던 in, and, or 조건도 모두 활용할 수 있습니다.

     

    db.collection.find(
    {status: "sleep"},
    {key: 0}
    )

    위와 같은 방법으로 key 부분을 결과에 포함하지 않도록 projection을 수행할 수 있습니다.

    0이 포함하지 않는 것, 1은 포함하는 것입니다.

     

    Update Operation

    https://www.mongodb.com/docs/manual/crud/

    updateMany, updateOne, replaceOne 등의 문법이 존재합니다.

     

    db.collection.updateOne(
      { name: "Brazil" },
      { $set: { age: 7 } }
    );

     

    위의 쿼리는 updateOne operation을 활용하여 filter와 action을 넣어줄 수 있습니다.

    이름이 Brazil인 회원을 찾고 해당 회원의 나이를 7로 변경하는 쿼리입니다.

     

    update를 수행할 때는 3가지 기능을 제공합니다.

    • $set : 해당 필드에 새로운 값 할당
    • $unset: 해당 필드 제거
    • $replaceWith: 완전히 새로운 값 할당

     

    만약 upsert 옵션이 활성화되어 있다면 update 할 문서가 없을 때 새로운 문서를 만들어냅니다.

     

    Delete Operation

    deleteMany, deleteOne 문법이 존재합니다.

    collection에서 문서를 제거할 수 있습니다.

     

     

    delteMany 문법

    db.collection.deleteMany(
       <filter>,
       {
          writeConcern: <document>,
          collation: <document>
       }
    )

     

     

    참고자료

    https://www.mongodb.com/docs/manual/crud/

    https://mongoplayground.net/

    https://coding-start.tistory.com/286

     

    '프로젝트 > mongoDB' 카테고리의 다른 글

    Spring Boot + Kotlin + MongoDB로 CRUD 해보기  (0) 2024.02.12
    MongoDB 동시성 제어  (0) 2024.02.11
    MongoDB Data Modeling  (0) 2024.02.06
    MongoDB Aggregation Operations  (0) 2024.02.05
    MongoDB란?  (0) 2024.01.06

    댓글

Designed by Tistory.