MongoDB 기본적인 사용법

앞글에서 docker를 이용하여 MongoDB를 올리는 법에 대해 다루었다. 이 글에서는 MongoDB의 몇개의 기본적인 개념과 CRUD를 구현 하는 방법에 대해 다룰 예정이다. 이 글에서는 DataGrip query consol를 이용하여 설명할 예정이다.

Collections

RDB에는 Table 개념이 있듯이 MongoDB에는 Collection이 있다. Collection은 Documents의 집합이라고 볼수 있다.

Create Collection

Collection을 만드는 방법은 간단하다. 아래 query가 실행하는 동시에 만약 해당하는 collection이 없으면 해당 collection를 만든다. inserOne과 createIndex 두 명령어만이 새로운 collection을 만들 수 있다.

db.test.insertOne( { x: 1 } )
db.test1.createIndex( { y: 1 } )

** 주의: Collection 이름은 MongoDB의 Naning 규칙을 따라야 한다.

만약 Collection에 관하여 여러가지 옵션을 설정할 필요가 있다면 아래 명령어를 이용하여 Collection을 만들 수 있다.

db.createCollection( <name>,
   {
     capped: <boolean>,
     timeseries: {                  // Added in MongoDB 5.0
        timeField: <string>,        // required for time series collections
        metaField: <string>,
        granularity: <string>
     },
     expireAfterSeconds: <number>,
     autoIndexId: <boolean>,
     size: <number>,
     max: <number>,
     storageEngine: <document>,
     validator: <document>,
     validationLevel: <string>,
     validationAction: <string>,
     indexOptionDefaults: <document>,
     viewOn: <string>,              // Added in MongoDB 3.4
     pipeline: <pipeline>,          // Added in MongoDB 3.4
     collation: <document>,         // Added in MongoDB 3.4
     writeConcern: <document>
   }
)

기본적인 CRUD

Insert

db.users.insert({username: "smith"})

위에서 설명 했듯이 Insert 명령어를 실행하는 동시에 만약 users라는 collection이 없으면 자동 생성한다.

Read(Find)

find 명령을 통하여 DB에 있는 데이터를 읽을 수 있다.

db.users.find()

결과 값을 아래와 같이 볼 수 있다.

[
  {
    "_id": {"$oid": "61873b253270f00a2c30c31d"},
    "username": "smith"
  },
  {
    "_id": {"$oid": "61873bb53270f00a2c30c31f"},
    "username": "jones"
  }
]

특정 조전을 이용하여 조회하기

db.users.find({username: "jones"})

결과는 아래와 같다. DB에 있는 두개 결과 중 jones만 조회에서 나왔다.

[
  {
    "_id": {"$oid": "61873bb53270f00a2c30c31f"},
    "username": "jones"
  }
]

여러조건을 이용하여 검색

#and 조건
db.users.find({ $and: [
... { _id: ObjectId("552e458158cd52bcb257c324") },
... { username: "smith" }
... ] })
#or 조건
db.users.find({ $or: [
... { username: "smith" },

... { username: "jones" }
... ]})

결과는 예상한 결과와 일치하게 나와서 여기에는 붙여 넣지 않는다.

Update

기록된 document를 수정하려고 하면 $set 명령어를 사용하여 업데이트 하면 된다. 사용법은 아래와 같다.

db.users.update({username: "smith"}, {$set: {country: "Canada"}})
  • update 구분 사용 시 주의 할 점, $set를 사용하지 않고 아래와 같이 명령어를 실행하면 username이 smith라는 document는 country: "Canada" 인 document로 대체 된다.
db.users.update({username: "smith"}, {country: "Canada"})

$set을 이용하여 업데이트 할 수 있지만 매번마다 모든 document를 다시 써야 하는 번거로움이 있다. 예를 들어 하나의 키에 속성을 추가하고 싶을때는 $addToSet이나 $push를 사용하면 된다.

db.users.update( {"favorites.movies": "Casablanca"},
...     {$addToSet: {"favorites.movies": "The Maltese Falcon"} },
...           false,
...           true )

$addToSet에는 두개의 파라미터가 필요한데 첫번째는 만약 존재하지 않으면 insert할지 결정하고 두번째 파라미터는 여러개를 업데이트 할지 결정한다. MongoDB는 다른 요구사항이 없으면 기본적으로 1개만 적용 하게끔 설계되었다.

Delete

db.users.remove()

아무조건 없이 명령어를 실행하면 users colection의 모든 내용을 제거 한단.

조건을 붙이려면 파라미터에 조건을 넣으면 된다.

db.users.remove({"favorites.cities": "Cheyenne"})

remove 명령어는 기본적으로 contents을 지우는 역할을 한다.

만약 colection을 지울려면 drop()명령어를 써야 한다.

마치며

MongoDB의 기본적인 CRUD에 대해 알아 보았다. RDBMS를 다루어 봤던 나로써는 MongoDB의 방식이 휠씬 더 간편한것 같다. 기회가 되면 복잡한 query문도 작성하여 RDBMS에서의 사용법과 비교할 예정이다.

Refernce:

MonggoDB in Acction, Second Edition

https://docs.mongodb.com/manual/reference/limits/#std-label-restrictions-on-db-names

 

MongoDB Limits and Thresholds — MongoDB Manual

Docs Home → MongoDB ManualMongoDB Limits and ThresholdsThis document provides a collection of hard and soft limitations of the MongoDB system.BSON Document SizeThe maximum BSON document size is 16 megabytes.The maximum document size helps ensure that a s

docs.mongodb.com

 

'DataBase' 카테고리의 다른 글

ORM 장단점  (0) 2021.12.12
Postgres Failover 방법  (0) 2021.12.12
PostgreSQL 설치부터 이중화까지  (0) 2021.12.12
MongoDB 개념 및 docker로 서비스  (0) 2021.11.07
Docker로 PostgreSQL를 서비스 하기  (0) 2021.11.03