티스토리 뷰

Database

MongoDB CRUD

조묵헌 2018. 5. 14. 12:35

몽고DB의 기본적인 데이터 추가, 조회, 수정, 삭제에 대해 알아보겠습니다.

Insert

특정 collection에 데이터를 삽입하기 위해서는 insert() 명령을 사용합니다.

// db.collection.insert()
db.posts.insert(
  {
    "title": "MongoDB",
    "description": "MongoDB is NoSQL DB..."
  }
)
//=> WriteResult({ "nInserted": 1 })

db에 데이터 삽입 시, 실행 결과 보고를 위해 항상 WriteResult가 리턴됩니다.

BSON Datatype

String        # "MongoDB is NoSQL DB..."
Number        # 42
Boolean        # true
Array            # ["alice", "bob"]
Object        # {"name": "alice"}
Null            # null
ObjectId    # ObjectId()
Date            # ISODate()

예시

{
  "createdAt": new Date(2018, 4, 15),  // 2018년 5월 15일
  "comments": ["hello", "world", "foo"],
  "awesome": 7,
  "ratings": {"like": 42, "unlike": 5}
}

Find

Collection의 데이터를 조회하기 위해서는 find()를 사용합니다.

// db.collection.find()
db.posts.find()

"_id": ObjectId("559f07d741894edebdd8aa6d") : 자동으로 생성되는 Unique Id는 각 도큐먼트를 식별하기 위한 식별자로 추가됩니다.

Query

Query : field / value 쌍으로 표현하여 일치하는 도큐먼트를 리턴합니다.

Array의 값은 개별로 처리되며, 객체의 값은 dot notation으로 탐색할 수 있습니다.

// db.collection.find({"field": "value"})
db.posts.find({"title": "MongoDB"})

// array의 값으로 탐색
db.posts.find({"comments": "hello"})
// Object의 키/값으로 탐색
db.posts.find({"awesome": 7})

// 하나 이상의 쿼리로 탐색
db.posts.find( 
  {"title": "MongoDB", "awesome": 7}
)

Query 비교 연산자 - $gt $gte $lt $lte $ne

/* 10 미만 검색 */
db.posts.find( {"awesome": {"$lt": 10}} )

/* 5 초과 10 미만 검색 */
db.posts.find( {"awesome": {"$gt": 5, "$lt": 10}} )

/* Not Equal */
db.posts.find( {"title": {"$ne": "MongoDB"}} )

Projection - 반환할 필드 선택하기

find()의 두번째 파라미터로 Projection을 사용합니다.

  • 항목을 true로 설정하여 보고싶은 필드를 지정할 수 있습니다.
  • 항목을 false로 설정하여 보고싶지 않은 필드를 지정할 수 있습니다.
  • 하나의 쿼리에서 true와 false를 같이 사용할 수는 없습니다. 단, _id 는 예외
// db.collection.find( {}, {"field": Boolean} )
db.posts.find(
    {"awesome": {"$gte": 5}},
  {"title": true, "description": true}  // title 및 description 필드만 보기
)

/* awesome 필드 보지 않기 */
db.posts.find(
  {},
  {"awesome": false}
)

/* _id 제외하기 */
db.posts.find(
  {},
  {"title": true, "description": true, "_id": false}
)

count() Cursor - 항목 카운팅

find() 메서드는 cursor 객체를 리턴합니다. 리턴한 문서의 갯수가 20개를 초과할 경우 cursor는 문서를 20개씩 iterate 하여 보여준게 되며, 다음 20개의 문서를 반환하기 위해서는 it 을 입력하여 확인할 수 있습니다.

it  // 다음 batch 반환

/* 문서 갯수 카운팅 */
db.posts.find().count()
//=> 80

sort() Cursor

/* sort(): -1 desc, 1 asc */
db.posts.find().sort({ "awesome": 1 })

skip() & limit() - Paginating

/* page 당 10개씩 pagination 하기 */
// Skip 0, Limit 10
db.posts.find().limit(10)          // Page 1
// Skip 10, Limit 10
db.posts.find().skip(10).limit(10)  // Page 2
// Skip 20, Limit 10
db.posts.find().skip(20).limit(10)  // Page 3

Delete

remove()

매칭되는 모든 도큐먼트를 지우므로 사용시 주의해야 합니다.

// db.collection.remove({"field": "value"})
db.posts.remove({"title": "MongoDB"})

Update

update() - $set

가장 처음 매칭되는 도큐먼트 하나만 업데이트하기

// db.collection.update( {"field": "value"}, {"$set": {"field": value}} )
db.posts.update(
  {"title": "MongoDB"},
  {"$set": {"description": "MongoDB is ..."}}
)

multi - 선택된 모든 도큐먼트를 업데이트하기 위한 옵션입니다.

// db.collection.update( {"field": "value"}, {"$set": {"field": value}}, {"multi": true} )
db.posts.update(
  {"title": "MongoDB"},
  {"$set": { "description": "MongoDB is ..." }},
  {"multi": true}
)

Array 타입의 필드에서 특정 항목을 업데이트하기 위해서는 해당 항목의 인덱스 값을 사용합니다.

db.posts.update(
    {"title": "MongoDB"},
  {"$set": {"comments.2": "bar"}}
)

Object(Embedded) 필드에서 키의 값을 변경하기 위해서는 해당 항목의 키값을 사용합니다.

db.posts.update(
    {"title": "MongoDB"},
  {"$set": {"ratings.like": 12}}
)

$inc - 숫자 increment

도큐먼트가 존재하는 경우,, 존재하는 도큐먼트의 항목 값 증가시키기위해 $inc 명령을 사용합니다.

db.posts.update(
    {"title": "MongoDB"},
  {"$inc": {"awesome": 1}}
)

upsert - 도큐먼트가 없을 경우에는 해당 도큐먼트를 생성하기 위해 upsert 옵션을 사용합니다.

db.posts.update( 
  {"title": "MongoDB"}, 
  {"$inc": {"awesome": 1}}, 
  {"upsert": true} 
)

$unset

도큐먼트에서 특정 field를 삭제하기 위해 사용합니다.

db.posts.update(
    {},                         // 모든 도큐먼트를 쿼리
  {"$unset": {"category": ""}},  // value에 상관없이 모든 필드 삭제
  {"multi": true}             // 모든 도큐먼트에 적용
)

$rename

Field Name을 변경하기 위해 사용합니다.

db.posts.update(
    {},
  {"$rename": {"category": "tag"}},  // "변경전 필드명": "변경할 필드명"
  {"multi": true}
)

'Database' 카테고리의 다른 글

MongoDB 설치와 실행  (0) 2018.05.11
MongoDB 기초  (0) 2018.05.11
MySQL Index, Join, Grant  (0) 2018.05.11
MySQL Query CRUD  (0) 2018.05.11
MySQL 사용하기  (0) 2018.05.11
댓글
공지사항
최근에 올라온 글
최근에 달린 댓글
Total
Today
Yesterday
링크
«   2024/03   »
1 2
3 4 5 6 7 8 9
10 11 12 13 14 15 16
17 18 19 20 21 22 23
24 25 26 27 28 29 30
31
글 보관함