28
MongoDB 로 로로로로 CRUD 대대대대대대대 Jinwook Jeong

Mongo DB로 진행하는 CRUD

Embed Size (px)

Citation preview

Page 1: Mongo DB로 진행하는 CRUD

MongoDB로 진행하는 CRUD

대구개발자그룹Jinwook Jeong

Page 2: Mongo DB로 진행하는 CRUD

MongoDB

Documents

• 데이터의 기본 단위는 문서• 문서의 특징

– 4MB 의 제한을 가짐– JSON 과 같이 Key-Value Pair 형태로 되어 있음

http://docs.mongodb.org/

Page 3: Mongo DB로 진행하는 CRUD

MongoDB

Collection

• 컬렉션은 문서의 모음으로 , table 과 같은 개념• 스키마를 가지지 않음

http://docs.mongodb.org/

Page 4: Mongo DB로 진행하는 CRUD

MongoDB

Query

• query 의 구성은 collection, query criteria, modifer 로 구성됨

http://docs.mongodb.org/

Page 5: Mongo DB로 진행하는 CRUD

MongoDB

Data Modification

• Data modification 은 create, update, delete 의 operation 을 이용함

• users collection 에 document 의 추가예

http://docs.mongodb.org/

Page 6: Mongo DB로 진행하는 CRUD

MongoDB

BSON

• BSON(Binary JSON) 은 JSON 의 Binary 표현 • JSON 은 파워풀하지만 , binary 데이터로 저장할 수 없음

– MongoDB 는 BSON 을 이용하여 데이터를 저장함– 예 : {"hello": "world"}

\x16\x00\x00\x00\x02hello\x00\x06\x00\x00\x00world\x00\x00

Page 7: Mongo DB로 진행하는 CRUD

MongoDB

Read Lock 과 Write Lock

• DB 별 Read Lock 과 Write Lock 을 가짐• read Lock 은 여러 Operation 에서 공유가 가능한 반면 , write

olock 은 하나의 Operation 에서 사용가능• 우선권

– write lock 이 read lock 보다 우선권을 갖는 이유로 , write 작업이 많을때 DB Read 작업을 할 수 없게 됨

Page 8: Mongo DB로 진행하는 CRUD

MongoDB

몽고 DB 실행

• 서버실행 : mongod --dbpath d:\mongo• 몽고 DB 쉘 : mongo

– 데이터 조작을 위한 몽고쉘 ( 자바스크립트 쉘 ) 을 제공한다 .

Page 9: Mongo DB로 진행하는 CRUD

MongoDB

몽고 DB 의 내부적인 특징

• 컬렉션은 스키마가 없는 테이블로 생각할 수 있다 .– 데이터의 기본 단위는 문서이며 , 컬렉션은 문서의 모음이다 .

• 모든 문서는 문서컬렉션 내에 유일키를 가진다• 데이터형과 대소문자를 구분한다

– {“foo”:3} 와 {“foo”:”3”} 는 다르다• 컬렉션 이름제약

– 몽고 DB 에서 정의한 함수명은 컬렉션이름이 될 수 없음– ex : db.version

Page 10: Mongo DB로 진행하는 CRUD

MongoDB

MongoDB 쉘의 기본명령어

• use [databasename] – 데이터베이스 선택

• db – 현재 선택된 DB 이름 ( 변수 ) 확인

• show dbs– show database names

• show collections– show collections in current database

• db.[collection-name].drop()– collection 삭제

• show users– show users in current database

• show profile

Page 11: Mongo DB로 진행하는 CRUD

MongoDB

MongoDB 쉘과 자바스크립트

• 자바스크립트의 for 루프 사용

• 함수호출

var collections=[“my”,”name”,”is”,”wook”];for (i in collections){

doStuff(db.blog[collections[i]]);}

function factorial (n) { if (n <= 1) return 1; return n * factorial(n - 1); }factorial(5);

Page 12: Mongo DB로 진행하는 CRUD

MongoDB

MongoDB 쉘에서의 CRUD

• create– db.blog.insert({"key1":"value1"})

• read– db.blog.find()

• 모든문서 반환– db.blog.findOne()

• 한문서 반환• db.blog.findOne({"key1":"value1"})

Page 13: Mongo DB로 진행하는 CRUD

MongoDB

MongoDB 쉘에서의 CRUD

• Update– db.blog.update({“key1":“value1“},{“key1”:”value2”})

• 갱신하려는 문서의 조건과 업데이트 데이터 필요– post.comment=[]– db.blog.update({title:"My Blog Post"},post)

• Delete– db.blog.remove({“key1":“value1"})– db.blog.remove({_id:

ObjectId('55badd91c79bcbac2c3c1b95')})

Page 14: Mongo DB로 진행하는 CRUD

MongoDB

Operator

• Operator– Update 와 관련된 연산자– 분류

• query and projection operators– comparison : eq,gt,gte,lt,lte,ne,in,nin– logical : or, and, not, nor– Element : exists, type– Evaluation : mod, regex,text,where– Geospatial : geowithin, geoIntersects,near, nearsphere– array : all, elemMatch, size,– comments : comment– Projection Operators : $, $elemMatch, meta, slice

• update operators– Fields : inc, mul,rename, setonInsert, set, unset, min, max, cur-

rentDate– Array : $, addtoSet, pop, pullAll, pull, pushAll, push– Modifier : each, slice, sort, position– Bitwise : bit– Isolation : isolated

Page 15: Mongo DB로 진행하는 CRUD

MongoDB

Operator

• aggregation pipeline operators– Stage operators : project, match, redact, limit, skip, unwind,

group, sort, geoNear, out– Boolean operators : and, or, not– Set operators : setEquals, setIntersection, setUnion, setDiffer-

ence, setIsSubset, anyElementTrue, allElementsTrue– Comparison operators : cmp, eq, gt, gte, lt, lte, ne– Arithmetic Operators : add, substract, multiply, divide, mod – String Operators : concat, substr, toLower, toUpper, str-

casecmp– TextSearch Operators : meta– Array Operators : size– Variable Operators : map, let– Lteral Operators : literal– Date Operators : dayofYear dayofMonth, dayOfWeek, year,

month, week, hour, minute, second, millisecond,dateToString– Conditional Expressions : cond, ifNull– Accumulatros : sum, avg, first, last, max, min, push, addToSet

Page 16: Mongo DB로 진행하는 CRUD

MongoDB

Query Modifiers

• Modifiers– 제한과 관련된 연산자– comment,explain, hint, maxScan, maxTimeMS, max, min, or-

derBy,returnKey,showDiskLoc,snapshot,query,

http://docs.mongodb.org/manual/reference/operator/

Page 17: Mongo DB로 진행하는 CRUD

MongoDB

주요 Operator

• push– array 에 특정 값을 append 함

• The $push operator appends a specified value to an array.

– Element 마지막에 item 추가– db.blog.update({}, {"$push" : {"x" : 1}})

• 마지막 요소부터 마지막 item 에 추가– db.blog.update({"score":1}, {"$push" : {"x" : 3}})

• 조건을 주어서 추가

db.blog.insert({"key1":"value1"})db.blog.update({"key1":"value1"},{$push : {"key2":"value2"}})

http://docs.mongodb.org/manual/reference/operator/update/push/

append 됨

Page 18: Mongo DB로 진행하는 CRUD

MongoDB

주요 Operator

• 증감관련– $inc ( 증가 )– db.blog.insert({"score":1})– db.blog.update({"score":1},{"$inc":{"key":20}})

Page 19: Mongo DB로 진행하는 CRUD

MongoDB

주요 Operator

• each– multiple value 를 array field 에 붙여넣음

db.blog.insert({"key1":"value1"})db.blog.update( {"key1":"value1"}, { $push: { scores: { $each: [ 90, 92, 85 ] } } })

Page 20: Mongo DB로 진행하는 CRUD

MongoDB

주요 Operator

• 키관련– $set ( 키추가 )

• db.blog.insert({"score":1})• db.blog.update({"score":1},{"$set":{"key":10}})

– $unset ( 키삭제 )• db.blog.update({"score":1},{"$unset":{"key":1}})

Page 21: Mongo DB로 진행하는 CRUD

MongoDB

주요 Operator

• 대소비교– $gte >= , $lte <=, $gt >, $lt <– db.blog.insert({"score":1})– db.blog.find({"score":{"$gte":1,"$lte":2}})

• not– 1 과 일치하지 않는 문서 찾기– db.blog.find({"score":{"$ne":1}})

Page 22: Mongo DB로 진행하는 CRUD

MongoDB

주요 Operator

• Size

db.food.insert({"_id" : 1, "fruit" : ["apple", "banana", "peach"]})db.food.insert({"_id" : 2, "fruit" : ["apple", "kumquat", "orange"]})db.food.insert({"_id" : 3, "fruit" : ["cherry", "banana", "apple"]})db.food.find({"fruit":{"$size":3}})

Page 23: Mongo DB로 진행하는 CRUD

MongoDB

조건절

blog = db.analytics.findOne({url : "/blog"})if (blog) {blog.pageviews++;db.analytics.save(blog);}else {db.analytics.save({url : "/blog", pageviews : 1})}

else 의 여는 괄호가 바로 오도록 주의

upsert 가 없는 경우

db.analytics.update({"url" : "/blog"}, {"$inc" : {"pageviews" : 1}}, true)

upsert 가 있는 경우해당숫자만큼 증가( 문서가 없으면 새로 할당 )

• Upserts– update 의 특별한 타입 . 문서가 없을때 생성 , 있으면 업데이트

Page 24: Mongo DB로 진행하는 CRUD

MongoDB

조건절

• Bulk 기반 Upserts– write operations 의 리스트 기반으로 upsert 실행

Bulk.find(<query>).upsert().update(<update>); Bulk.find(<query>).upsert().updateOne(<update>); Bulk.find(<query>).upsert().replaceOne(<replacement>);

http://docs.mongodb.org/manual/reference/method/Bulk.find-.upsert/

var bulk = db.blog.initializeUnorderedBulkOp();bulk.find( {"key1":"value1"} ).upsert().replaceOne( { item: "abc123", status: "P", points: 100, });bulk.execute();

Page 25: Mongo DB로 진행하는 CRUD

MongoDB

데이터형

• 불리언형 : {“x”:true}• 부동소수점형 : {“x”:3.14},{“x”:3}• 문자열형 : {“x”:”wook”}• 날짜형 : {“x”:new Date()}• Undefined 형 : {“x” : undefined}• 배열 : {“x”:[“a”,”b”,”c”]}• 내장문서 : {“x” : {“daegu”,”daejeon”}}

• 문서 “ X” 의 값으로 , 내장문서를 가질 수 있음• 객체 ID 형 : {“x” : objectId()}

– 객체 ID 형 문서의 고유한 12 바이트 ID

• ....

Page 26: Mongo DB로 진행하는 CRUD

MongoDB

ObjectIds

• ObjectID– _id 의 기본 데이터형– 전통적인 auto increment 방식의 primary 키의 대체방식으로 ,

다중서버에서 고유 값을 가질수 있도록 ObjectID 가 생성됨– 키구성

• Time : unix timestamp• Machine : md5 hash of machine name• Process id : pid• Counter : incrementing value starting with a random number

Page 27: Mongo DB로 진행하는 CRUD

MongoDB

Query - Regex

• Regex– String match

– Digit match

• 문자열만 매칭됨을 유의

db.blog.insert({"name":"daegu"})db.blog.find({"name":/daegu/})

db.blog.insert({"year":1990})db.blog.find({"year":/^(199\d|200\d|2010)$/})

Page 28: Mongo DB로 진행하는 CRUD

MongoDB

Performance Test

• Modifier Test

db.tester.insert({"x" : 1})var timeInc = function() {var start = (new Date()).getTime();for (var i=0; i<100000; i++) {db.tester.update({}, {"$inc" : {"x" : 1}});db.getLastError();}var timeDiff = (new Date()).getTime() - start;print("Updates took: "+timeDiff+"ms");}timeInc()