이번 포스팅에서는 CRUD operation에 대해서 개괄적으로 이야기해볼 생각이다. 개괄적으로다. 너무 자세하게 하는 것은 어짜피 메뉴얼만 못 하므로 개괄적으로 이야기해보려고 한다. 이야기하다가 중요한 개념이 있다고 생각하면 그 부분은 그래도 꼭 언급하고 갈터이니 그렇게 걱정하지 않아도 된다.
CREATE operation
MySQL과 MongoDB에서 다른 것 중 하나가 Create operation이다. MySQL 에서는 CREATE DATABASE ... 와 같이 테이블 생성을 위한 명령어가 따로 있는가 반면, MongoDB는 unstructured, schema-free database이기 때문에 굳이 Schema를 정하는 과정이 필요 없다. 따라서 사용하고 싶은 데이터베이스의 이름을 정해서 use 명령어를 Mongoshell에 입력하면 된다.
'show databases' 명령어를 통해 데이터베이스가 생성되어있는지 확인을 하면 life database가 생성되어있지 않는 것을 확인할 수 있다.
database를 실제로 생성하려면 하나 이상의 document를 가진 collection이 최소 한 개 이상 있어야 한다.
CREATE collection
그러면 한번 만들어보자. collection 을 생성하는 것 역시 schema-free 이기 때문에 특별한 명령어가 없다.MySQL에서는 CREATE TABLE ... 과 같은 명령어가 있지만 MongoDB는 그렇지 않다. 따라서 그냥 insert함수를 써서 collection에 document를 삽입해주면 된다. 아래와 같다.
document를 세 개 이상 삽입하고 싶으면 아래와 같이 array 형식으로 바꿔서 삽입해도 된다.
지금 'show dbs' 명령어를 다시 실행시켜보면 life database가 생성되어있는 것이 확인된다.
READ operation
MongoDB에서 document를 query하기 위해서는 find operation을 사용하면 된다.
# insert() definition, docs.mongodb.org
db.collection.find(<criteria>, <projection>)
<criteria> : Optional, Should be document type
<projection> : Optional, Should be document type
위와 같이 사용할 수 있다. 아래에 몇가지 예시를 들어보면 조금 더 이해가 쉬울 것이다.
# without <projection>
※ $gt는 query operator이다. 아래에 다른 query operator도 설명할 것이니 참고하면 된다.
# with <projection>
※ _id field는 자동으로 1로 세팅된다. 따라서 _id field를 보고 싶지 않을 때는 _id:0과 같이 손수 명시를 해주어야 한다.
# query operator
$gt Matches values that are greater than the value specified in the query.
$gte Matches values that are greater than or equal to the value specified in the query.
$in Matches any of the values that exist in an array specified in the query.
$lt Matches values that are less than the value specified in the query.
$lte Matches values that are less than or equal to the value specified in the query.
$ne Matches all values that are not equal to the value specified in the query.
$nin Matches values that do not exist in an array specified to the query.
find() operator는 cursor를 return 한다. cursor가 무엇이냐? find()의 결과에 대하나 pointer라고 생각하면 된다.
UPDATE operation
UPDATE문은 아래와 같은 구문으로 사용할 수 있다.
# update() syntax
db.collection.update(query, update, options)
<query> : Same as query operator of find()
<update>: Update operator is given below.
multi : Optional. Modify every document that matches to <query>. Set as fault by default
upsert : Optional. Create document when no query is matched. Set as fault by default
writeConcern : Optional.
update operator에 대한 예시는 아래의 그림을 통해 확인하자.
"PS Lee" document의 age key에 3을 더하라는 명령어다. $inc라는 update operator를 사용했다. 아래에 더 많은 update operator가 소개되어 있으니 참고하길 바란다.
# update operator, docs.mongodb.org
$currentDate Sets the value of a field to current date, either as a Date or a Timestamp.
$inc Increments the value of the field by the specified amount.
$max Only updates the field if the specified value is greater than the existing field value.
$min Only updates the field if the specified value is less than the existing field value.
$mul Multiplies the value of the field by the specified amount.
$rename Renames a field.
$setOnInsert Sets the value of a field if an update results in an insert of a document. Has no effect on update operations that modify existing documents.
$set Sets the value of a field in a document.
$unset Removes the specified field from a document.
update() operator에서 multi option은 매칭되는 모든 document에 대해서 update를 적용시키도록 하는 option이다. 일반적으로 생각하기에 '당연한거 아니야?' 라고 생각할 수 있는데 MongoDB는 당연하게 설정되어있지 않드라.
DROP operator
drop() 함수를 통해 collection을 drop할 수 있다.
db.collection.drop()과 같이 사용할 수 있고 parameter를 사용하지 않는다.
Delete operator
특정 document를 삭제하려고 한다면, delete()함수를 쓰면 된다.
# delete() syntax
db.collection.delete(<query>, {justOne, writeConcern})
<query> : document type. Same as query operator of find()
justOne : boolean type. Update operator is given below.
<writeConcern>: document type
휴 간단하게 CRUD는 끝내버리자.훨씬더 자세하게 쓸 수 있지만 굳이 적지는 않겠다. 내가 manual보다 잘 쓸 자신은 없고 manual을 보면서 연구하는 것이 조금 더 IT하는 사람다운 접근이기 때문이다.
MongoDB 포스팅을 하기로 했으므로 계속 할 생각이지만, 다른 분석 포스팅들보다는 대략적으로 사용법만 언급하겠다. 물론 중요한 개념, aggregation, mapreduce, index 등등의 부분에 한해서는 나만의 디테일함을 보여주겠다!!
이번 포스팅은 여기서 마치고 다음 포스팅은 index나 aggregation 관련이지 않을까 싶다. 마지막으로 Reference로 Mongodb manual 링크를 남겨둔다. 아래의 문서를 보고 연구하며 MongoDB를 배워보자.
Reference
http://docs.mongodb.org
'Big Data Tech' 카테고리의 다른 글
[Hadoop] Basic Example : WordCount (2) | 2015.01.31 |
---|---|
[Hadoop] Introduction of Hadoop (0) | 2015.01.31 |
[MongoDB] MongoDB Aggregation (0) | 2014.11.24 |
[MongoDB] Introduction of MongoDB and its fundamental (0) | 2014.11.09 |
[MongoDB] 시작하며... (0) | 2014.11.02 |