NoSQL & MongoDB PLAN 정보기술 Consultant 주종면 jina6678@paran.com 010-3864-1858 1
- 목차 - 1 장. NoSQL -NoSQL 의시대적요구 - 클라우드컴퓨팅을위한 DBMS -NoSQL시장및직무동향 - MongoDB 주요특징 2 장. MongoDB 사용방법및활용 - MongoDB 설치및데이터처리 - 논리적구조와물리적구조 - 메모리구조 - MongoDB 주요기능 3 장. NoSQL 를위한 Data Modeling - 데이터베이스모델링 & 설계 Pattern - NOSQL 전문가가되기위해준비해야할일 2
1 NoSQL 개념 3
NoSQL? No SQL Not Only SQL Non-Relational Operational Database SQL 4
NoSQL 의시대적요구 1960 년 1970/1980 년 1990 년 1995 년 1998 년 2000 년 2010 년 RS-232/RS-485 환경 LAN 환경 인터넷환경 (1세대) 인터넷환경 (2세대) 무선인터넷환경 (3 세대 ) Main (Host) 중심 Client/Server Cloud Computing Paradigm Paradigm Paradigm File System RDBMS NoSQL 5
NoSQL 의장점 1. 클라우드컴퓨팅환경에적합하다. 1) Open Source이다. 2) 하드웨어확장에유연한대처가가능하다. 3) 무엇보다 RDBMS 에비해저렴한비용으로분산처리와병렬처리가가능하다. 2. 유연한데이터모델이다 1) 비정형데이터구조설계로설계비용감소 2) 관계형데이터베이스의 Relationship 과 Join 구조를 Linking과 Embedded로구현하여성능이빠르다. 3. Big Data 처리에효과적이다 1) Memory Mapping 기능을통해 Read/Write 가빠르다. 2) 전형적인 OS 와 Hardware 에구축할수있다. 3) 기존 RDB 와동일하게데이터처리가가능하다. 6
DBMS for NoSQL 7
NoSQL 제품군 1. Key-Value Database 3. Document Database 1) Amazon s Dynamo Paper 1) Lotus Notes 2) Data Model : Collection of K-V pairs 2) Data Model : Collection of K-V collection 3) 제품유형 : Riak, Voldemort, Tokyo* 3) 제품유형 : Mongo DB, Cough DB 2. BigTable Database 1) Google s BigTable paper 2) Data Model : Column Families 3) 제품유형 : Hbase, Casandra, Hypertable 4. Graph Database 1) Euler & Graph Theory 2) Data Model : nodes, rels, K-V on both 3) 제품유형 : AllegroGraph, Sones * Availablity( 유용성 ), Consistency( 일관성 ), Partitioning( 파티션닝 ) 에따른제품군구분 8
NoSQL 시장동향 9
NoSQL Funding 동향 참조자료 : 2011 년 7 월가드너그룹 10
NoSQL 관련직무동향 참조자료 : indeed.com 11
NoSQL 관련 LinkedIn 멤버동향 12
MongoDB Job 동향 * 2012 년 6 월 indeed.com 통계 13
NoSQL 제품별평가결과 평가기준 Tokyo*Cabinet * Tokyo Tyrant Berkerly DB Memcache DB Voldemort BDB JE REDIS MongoDB Write (Small Data Set) Write (Large Data Set) Random Read (Small Data Set) Random Read (Large Data Set) Speed 일관성 Storage 효율성 Horizontal 확장성 Manageability ( 관리성 ) Stability ( 안정성 ) Community Support * 2011 년 PerfectMarket 자료참조 14
MongoDB 주요특징 1) Humongos 라는회사의제품명이었으며현재 10gen 으로 회사명이변경되었다. 2) Document(JSON Type) 기반의데이터저장구조를제공한다. ( 경량의데이터교환형식인 JSON(JavaScript Object Notation) 타입을기반으로하며 JavaScript Programming Language, Standard ECMA-262 3 rd Edition-1999 근거로함 ) 3) Replica( 복제 )/Shard( 파티셔닝 ) 기능을제공한다. 4) MapReduce( 분산 / 병렬처리 ) 기능을제공한다. 5) CRUD(Create, Read, Update, Delete) 위주의다중트랜잭션처리도가능하다. 6) Memory Mapping 기술을기반으로 Big Data 처리에탁월한성능을제공한다. http://www.10gen.com/what-is-mongodb 15
Terminology _ID Field (Primary Key) JSON Field (Column) Collection (Table) emp 사원번호 사원명 직급 급여 부서번호 1 주종면 차장 300 10 2 주영현 과장 250 10 JSON Document (Row) 3 홍경옥과장 200 20 dept 4 홍길동부장 30 부서번호 부서명 5 유관순이사 550 40 10 전산과 20 총무과 Embedded & Linking 30 자재과 (RelationShip) 16
Shard Key (Partition Key) Partition Replica Sets (Snapshot) Replication 17
2 MongoDB 설치및데이터처리 18
SQL & NoSQL 19
설치환경및지원드라이버 Version 0.8 (2009 년 ) Version 1.3 (2010 년 ) Version 1.7 (2011년) Version 2.1.2 (2012 년 6 월 ) 1) 설치가능플랫폼. Windows 32 bit / 64 bit. Linux 32 bit / 64 bit. Unix Solaris i86pc / 64 bit. Mac OS X-32bit / 64 bit 2) 지원 Language Driver. C / C# / C++. Java / Java Script. Perl / PHP / Python. Ruby / Erlang / Haskell / Scala 20
MongoDB 의시작 1) Mongod.exe DBMS 종류 실행파일 Client 툴 Mysql Mysqld.exe Mysql.exe Oracle Oracle.exe Sqlplus.exe MongoDB Mongod.exe Mongo.exe 2) Mongo.exe 21
Collection 생성과삭제 > db.createcollection ( emp, { chapped : false, size:8192 }); { "ok" : 1 } chapped : 해당공간이모두사용되면다시처음부터재사용할수있는데이터구조를생성할때 size : 해당 Collection의최초생성크기지정가능 > show collections emp > > db.emp.validate(); Collection의현재상태및정보분석 >{ "ns" : "test.emp", "firstextent" : "0:61000 ns:test.emp", "lastextent" : "0:61000 ns:test.emp", "extentcount" : 1, "datasize" : 0, "nrecords" : 0, "lastextentsize" : 8192, > db.emp.renamecollection( employees" ) 해당 Collection 이름변경 > db.employees.drop(); 해당 Collection 삭제 true 22
JSON 데이터타입. 경량의데이터교환형식인 JSON(JavaScript Object Notation) 타입을 근거로하며사람이읽고쓰기에용이하며기계가분석하고생성하기에 용이하다. (Name 과 Value 로구성됨 ). JavaScript Programming Language 와 Standard ECMA-262 3 rd Edition-1999 을근거로한다. (European Computer Manufacturers Association) { ename : 주종면 } Document Length Value Type \x16\x00\x00\x00 \x02ename\x00 \x06\x00\x00\x00 주종면 \x00\x00 23 Value Length
JSON 타입과데이터저장 주문 (ORD) Document > p = { ord_id : "2012-09-012345", customer_name : "Wonman & Sports", emp_name : "Magee", total : "601100", payment_type : "Credit", order_filled : "Y } > db.ord.save(p) > db.ord.find() * 하나의 Document 는반드시유일한값의 Object_ID 값이부여된다. 24
데이터의입력 / 수정 / 삭제 > db.emp.insert ({ eno : 1101, fname : JIMMY" }); > db.emp.insert ({ eno : 1102, fname : ADAM, lname : KROLL }); > db.emp.insert ({ eno : 1103, fname : SMITH, job : CLERK }); > db.emp.update ({ eno:1101 }, { $set: { fname : JOO } } ); > db.emp.update ({ eno:1102 }, { $set: { job : CHIEF } } ); > db.emp.update ({ eno:1103 }, { $set: { lname : STANFORD } } ); > db.emp.remove ({ eno: 1101}); > db.emp.find().sort ({eno:-1}); { "_id id" : ObjectId("4fe6852f5642c534a77fbdb1") ), "eno" : 1103, "fname" : "SMITH", "job" : CERK", "lname" : "STANFORD" } { "_id id" : ObjectId("4fe685195642c534a77fbdb0") ), "eno" : 1102, "fname" : "ADAM", "job" : "CHIEF", "lname" : "KROLL" } 25
SQL & NoSQL 비교 SQL Statement CREATE TABLE emp (empno Number, ename Number) INSERT INTO emp VALUES(3,5) NoSQL Statement db.createcollection( emp") db.emp.insert({empno:3, ename:5}) SELECT * FROM emp db.emp.find() SELECT empno, ename FROM emp db.emp.find({}, {empno:1, ename:1}) SELECT * FROM emp WHERE empno=3 db.emp.find({empno:3}) p SELECT empno, ename FROM emp WHERE empno=3 SELECT * FROM emp WHERE empno=3 ORDER BY ename db.emp.find({empno:3}, {empno:1, ename:1}) db.emp.find({empno:3}).sort({ename:1}) 26
Oracle & NoSQL 비교 SELECT deptno, job, SUM(sal) AS msum, <- 부서별급여합계 COUNT(*) AS recs, <- 부서별인원수 AVG(sal) ASmavg mavg, < MIN(sal) AS mmin, <- 최소급여액 MAX(CASE <- 최대급여액 WHEN sal > 1000 <- 평균급여금액 THEN sal END) AS mmax FROM emp WHERE (hiredate > 01-01-1981' AND hiredate < 31-12-1983') AND sal > 800 GROUP BY deptno, job HAVING min(sal) > 0 ORDER BY recs DESC 대상 Table 과 Collection 검색조건 검색 Column 또는 Field Aggregate 또는 Procedure Logic Aggregate 또는 Procedure Logic Aggregate Filter 또는 Sorting db.runcommand ({ mapreduce: "emp", query: { hiredate : { $gt : '01-01-1981', $lt : '31-12-1983' }, sal : { $gt : 800 } }, map: function() { emit( { d1 : this.deptno, d2 : this.job }, { msum: this.sal, recs: 1, mmin: this.sal, mmax: this.sal > 1000 } ); }, reduce: function(key, vals) { var ret = { msum:0, recs:0, mmin:0, mmax:0 }; for (var i=0 ; i < vals.length; i++) { ret.msum += vals[i].msum; ret.recs += vals[i].recs; if (vals[i].mmin < ret.mmin) ret.mmin=vals[i].mmin; if (vals[i].mmax > 1000) ret.mmax=vals[i].mmax; } return ret; }, finalize: function(key, val) { val.mavg=val.msum/val.recs; return val; }, out: "result1", verbose: true }); db.result1.find ({"value.mmin": { $gt:0}}).sort({ "value.recs": 1}); 27
INDEX 생성과관리 > db.emp.ensureindex ({ eno: 1 }, { unique: true }); 1(Asc), -1 (Desc) > db.emp.dropindex ({ eno : 1 }); > db.emp.getindexes() { "v" : 1, "key" : { "eno" : 1 }, "unique" : true, "ns" : "test.emp", "name" : "eno_1" } > db.system.indexes.find() { "v" :1 1, "key" :{"eno" :1} }, "unique" : true, "ns" : "test.emp", "name" : "eno_1" } 28
GeoSpatial INDEX. 좌표에의해구성되는 2 차원구조로하나의 Collection 에 하나의 2D Index 를생성할수있다. 10 9 8 7 6 5 4 3 2 1 > for ( var i = 0; i < 100; i++) 1 2 3 4 5 6 7 8 9 db.square.insert ({ pos : [ i % 10, Math.floor( i / 10 ) ] } ) > db.square.ensureindex ({ pos : 2d }) > db.square.find({ pos : { $near : [5, 5] }}).limit(5) ) { pos : [ 5, 5 ] } { pos : [ 5, 4 ] } { pos : [ 4, 5 ] } { pos : [ 5, 6 ] } 10 { pos : [ 6, 5 ] } 29
Multi-Location Documents 오전 10:35 거래처 통화 위도:37.5685375 경도:126.9815316 오전 08:00 딸 통화 위도:37.535397 위도:37 535397 경도:127.0945116 오후 13:10 후배 통화 위도:37.5017141 경도:127.0305035 > db.tel_pos.save 01038641858, db tel pos save ({ mobile_no mobile no : 01038641858 last_pos : [[ 127.0945116, 37.535397], [ 126.9815316, 37.5685375], [ 127.0305035, 37.5017141]]}) > db.tel_pos.ensureindex( { last_pos : 2d }); 30
$nearsphere 오전 10:35 10 35 거래처 통화 위도:37.5685375 경도:126.9815316 3K Km 오전 08:00 딸 통화 위도:37.535397 경도:127.0945116 오후 13:10 후배 통화 위도 37 5017141 위도:37.5017141 경도:127.0305035 p > db.tel_p pos.find(( { last_p pos : { $ $nearsphere : [[ 127.0352915, 37.5360206], 3/6371] }}, {_id:0, last_pos : 0 }) 성수대교를 기준으로 반경 3 Km 이내 { "mobile_no" : "01038641858", last_pos : [ 127.0945116, 37.535397] } 딸과 통화 내역 { "mobile_no" : "01038641858", last_pos : [ 127.0305035, 37.5017141] } 후배와 통화 내역 31
논리적구조와물리적구조 32
MongoDB Architecture (Single Node) Virtual Memory Area Mongo.exe Server Process (Mongod) Data file Journal file SALES. NS (16MB) SALES.0 (64MB) Prealloc.0 (1GB) Prealloc.1 (1GB) Prealloc.1 (1GB) 33
Physical & Logical Architecture Plan Information Logical Technology. 구조 Physical 구조 MongoDB SALES. NS SALES.0 SALES.1 } Mongo MongoDB shell version: 2.0.2 connecting to: test > > use SALES switched to db SALES > > > db.createcollection( s_emp", {capped:false, size:100000}); 1) 32 Bit 에서 Namespace 의최초크기는 16MB 가할당되며 DataFile 은 32 MB 크기로생성된다. Next 크기는 32MB 의배수로증가하되최대 크기는 2GB 이다. (64 Bit 에서는 16MB, 64 MB 단위, Journing 은 1GB) 2) Namespace 에는 Collection 의 First Extent 와 LastExtent 에대한정보 와 Meta Data, 인덱스, FreeList 정보가저장된다. 34
Logical Architecture Database (Namespace+ DataFiles Collection Extent Data Record Document S_Emp Collection Data Record Data Record Data Record Data Record Data Record Data Record Length xnext xprev Document { _id: 1,. } Length xnext xprev Document { _id: 2,. } Length xnext xprev Document { _id: 3,. } Length xnext xprev Document { _id: 4,. } Length xnext xprev Document { _id: 5,. } Length xnext xprev Document { _id: 6,. } 1) MongoDB 의논리적구조는 Database Collections Extents Data Records Documents 로구성된다. 2) Collection 크기는최초생성시점에결정되며 Extent 기본크기는 8K 이며 데이터크기가작은경우에는 4K 로생성된다.( 사용자에의해결정가능 ) (Ex) db.createcollection( s_emp", {capped:false, size:100000}); 35
Structure Status 36
메모리구조 37
Memory Structure(64 Bit) Virtual Memory Area Mapped Cache Area Virtual Area Resident Area (Working Set) * 최초약 470 MB Journal Area 80 MB 190 MB 38 MB 160 MB ( 최초 21MB) 60 s 마다동기화 100 ms 마다 Data file Journal file SALES. NS (16MB) SALES.0 (64MB) Prealloc.0 (1GB) Prealloc.1 (1GB) Prealloc.1 (1GB) 38 db.serverstatus().mem
적정메모리요구사항 1) MongoDB 는 Direct Mapping 기법에의해데이터를처리하기때문에최초 메모리크기는생성되는 Namespace 와 Data-File 에맞는적정한 Mapped Area 크기가요구된다. (64 Bit 의경우최초 Namespace 16MB + 첫번째 Data-File 64MB) 2) 사용자의데이터를위한 Virtual Memory 와함께 MongoDB 서버를원활하게 운영하기위한 Resident Area 와 Journal Area 가요구된다. 이공간은 Mapped Area 크기에따라서버에의해동적으로할당된다. 3) Mapped Cache Area 크기가 2 GB 인경우요구되는 RAM 메모리는약 10 GB ~12 GB 정도가요구된다. SYSTEM 메모리가부족한경우전체공간의 80% 까지자동으로동적할당되며 Flushing 과 Segmentation Fault 가발생하여 성능저하현상이발생할수있다. (32 Bit 에서최소 4GB 이상요구 ) 39
MongoDB 주요기능 40
Sharding Collection Shard 1 주문번호 2012010100001 ~2012013100999 Shard 2 주문번호 2012020100001 ~2012022800679 Shard 3 주문번호 2012030100001 ~2012033100456 1) Sharding 의가장큰목적은파티셔닝을통한데이터분산처리와 성능향상을위한 Load Balancing 이다. 2) 또한, 빅데이터의효율적관리와백업및복구전략수립을위한 솔루션이기도하다. 41
MongoDB Architecture (Multi Node) Shared Mongod Mongod Mongod Config Server Mongod Mongod Mongod Mongod Mongod Mongod Mongod Mongod Mongod Route Server (MongoS) Route Server (MongoS) Mongo.exe Mongo.exe Mongo.exe Mongo.exe 42
Shard 환경설정 1) MongoS 프로세스를활성화한다. C:\> mongos --configdb 192.168.0.1:10000,192.168.0.2:10001,192.168.0.3:10002 2) Config Server 가설치된 Node 에서각 Node 가상호연결될수있도록등록한다. C:\> mongo localhost:27017/admin mongos에접속하여node 정보등록 mongos> mongos> db.runcommand( { addshard : "192.168.0.1 : 10000"} ); Node1 등록 { "shardadded" : "shard0000", "ok" : 1 } mongos> mongos> db.runcommand( { addshard : "192.168.0.2 : 10001"} ); Node2 등록 { "shardadded" : "shard0001", "ok" : 1 } mongos> mongos> db.runcommand( { addshard : "192.168.0.3 : 10002"} ); Node3 등록 { "shardadded" : "shard0002", "ok" : 1 } mongos> mongos> db.runcommand( {enablesharding : test } ); 해당 DB Shard 기능설정 { ok = 1 } > db.runcommand( {shardcollection : test.things, key : {_id : 1} } ); Shard Key { collectionsharded : test.things, ok : 1 } 43
Replica 기능 Replica Set Read/Write Primary Server OpLog 매 2 초마다상태체크 Read Secondary Server 매 2 초마다상태체크 Secondary Server For Backup 1) Heartbeat : 매2초마다Secondary 상태를체크한다. 2) Secondary 가 Down 되더라도복제만중지될뿐 Primary 에대한작업은정상적이다. 3) Primary가다운되면 Secondary가 Primary가된다. 4) OpLog는복제가실패하는경우를위해로그정보를저장해준다.( 기본크기 1GB) 44
Fail Over-1 Replica Set Primary Server Read/Write Primary Server Secondary Server For Backup 45
Fail Over-2 Replica Set Read Secondary Server Read/Write Pi Primary Server Secondary Server For Backup 46
환경설정 1) Primary DB 에서입력된데이터가 Secondary DB 에복제될수있도록데이터를입력한다. C:\> mongo 192.9.200.1:10000 > use testt > db.things.insert( { empno : 1101,ename : james,dept : account } ); > db.things.find(); {"_id":objectid("4f03b6c6e5c6022a325f7181"), "empno":1101, "ename":"james","dept":"account } 2) Secondary DB 에서복제된데이터를확인한다. C:\> mongo 192.9.200.2:10001 > use test > db.things.find(); Primary DB 에서생성된 Collection 과 Document {"_id":objectid("4f03b6c6e5c6022a325f7181"), "empno":1101, "1101 "ename":"james","dept":"account } ""j " "d t"" t } 47
보안 / 인증방법 1) 전형적인인증방식으로 MongoDB 를설치했던 O/S 계정의권한으로데이터베이스에접속할수있다. OS 인증방식 2) MongoDB 에서는해당시스템의 IP-Address 로만접속을허용하는 Network 인증방식을제공한다. ( 예 ) mongod --bind_ip 192.168.0.10 DB 인증방식 1) DBMS의가장보편적인인증방식으로미리사용자계정과암호를생성한뒤이계정명과암호를정확히입력한사용자를인증하는방법이다. ( 예 ) db.adduser( jimmy", joo") db.auth( jimmy", joo") 2) MongoDB에접속할때DB 인증방식을선택할수있다. ( 예 ) mongod --auth 또는 mongod --noauth 3) Replica Sets 환경을구현할때 Primary Server와 Secondary Server 간에인증을위해인증 Key 가요구된다. ( 예 ) mongod --keyfile 48
3 MongoDB 를위한 Data Modeling 49
Data Modeling 핵심 1) HOST 환경의파일시스템은프로세스중심의데이터구조설계였다면 클라이언트 / 서버환경의관계형 DB 는 Data 중심의설계를지향하였다. 반면에클라우드컴퓨팅환경의 NoSQL 은 Data 와프로세스, 모두를 설계의중심으로둔다. (Big Data 의수집및저장과함께유연성있는데이터처리도중요함 ) 2) Rich Document Structure 관계형 DB는정규화를통해데이터중복을제거하며무결성을보장하는설계기법을지향하지만 NoSQL은데이터의중복을허용하며비정규화된설계를지향한다. ( 관계형 DB가요구되었던당시와달리저장장치의 비약적발전과저렴한가격요인도설계에중요한요소임 ) 50
3) 관계형 DB 는 Entity 간의 Relationship 을중심으로데이터의무결성을 보장하지만불필요한 JOIN 을유발시킴으로써코딩양을증가시키고검색 성능을저하시키는원인을제공한다. NoSQL 은중첩데이터구조를설계 할수있기때문에불필요한 JOIN 을최소화시킬수있다. 4) 관계형 DB는 Entity 간의 N:M 관계구조를설계할수없지만 NoSQL은 N:M 관계구조를설계할수있고구축할수있다. 5) Document DB 는기본적으로 Schema 가없기때문에유연한데이터 구조를설계할수있다. 51
MongoDB Design 기준 1. 데이터조작은어떻게수행하는가? 1) Dynamic Query 사용여부 2) Secondary Indexes의사용여부 3) 원자적 Update의실행빈도 4) Map Reduce 의적용여부 2. Access Patterns 은어떤가? 1) Read와 Write의비율은? 2) Update Type은어떤가? 3) Data 의 Life Cycle은어떤가? 3. 스키마설계시고려사항은? 1) No Join을지향하는데이터구조설계 2) Linking & Embedded 조건은? 3) Document 저장은원자적요소기준으로설계 52
주문전표 주문번호 2012-09-01234509 012345 담당사원 Magee 고객명 Womansport 주문날짜 2012-09-20 선적날짜 2012-09-20 선적여부 주문총금액 601,100 지불방법 현금 30일이내 Y 항목번호제품명단가주문수량금액 1 Bunny Boot 135 500 67,500 2 Pro Ski Boot 380 400 152,000 3 Bunny Ski Pole 14 500 7,000 4 Pro Ski Pole 36 400 14,400 5 Himalaya Bicycle 582 600 349,200 6 New Air Pump 20 450 9,000 7 Prostar 10Pd.Weight 8 250 2,000 SUMMIT2 53
Schema 설계의주요특징 1) Embedded(Nested) & Linking 구조. 객체지향 Data 관계유형과관계형 Data 유형모두를설계할수있다. 주문 주문항목 주문주문항목 강한관계 (Strong Association) 부서 사원 부서사원 약한관계 (Weak Association) Object Oriented Database 관계 (Relationship) Relationship Database 54
MongoDB 데이터저장 (Embedded) db.ord.insert( { ord_id : "2012-09-012345", 주문공통정보 customer_name : "Wonman &S Sports", emp_name : "Magee", total : "601100", payment_type t : "Credit", order_filled : "Y", item_id : [ { item_id : "1", product_name : "Bunny Boots", item_price : "135", 주문상세정보 qty : "500", price : "67000 }, { item_id : "2", product_name : "Pro Ski Boots", item_price : "380", qty : "400", price : "152000 } ] } ) 55
MongoDB 데이터저장 (Manual Linking) > db.ord.insert( { ord_id : "2012-09-012345", customer_name : "Wonman & Sports", emp_name : "Magee", total t : "601100", payment_type : "Credit", order_filled : Y } ) 주문공통정보 > o = db.ord.findone( d d ({" "ord_id" : "2012-09-012345" 09 012345" } ) { "_id" : ObjectId("4fc21223e6cd4d2aadb38622"),. > db.ord_detail.insert( { ord_id : "2012-09-012345", item_id id : [ { item_id id : "1", product_name : "Bunny Boots", item_price : "135", qty : "500", price : 67000 }, { item_id : "2", product_name : "Pro Ski Boots", item_price : "380", qty : "400" price : "152000 } ], ordid_id : ObjectId("4fc21223e6cd4d2aadb38622 ) } ) 주문상세정보 qty : "400", > db.ord_detail.findone({ordid_id : o._id}) 56
2) Many To Many 관계구조. 관계형 Data 구조에서는제공하지않은다 - 대 - 다관계구조를생성할수있다. 제품 카테고리 ASUS EP121 Note Book Samsung eslate 7 Slate PC ipad 3 Tablet 57
N:M 관계 (MongoDB) > db.category.find() { "_id" : ObjectId("4fc23ac83153207db00dfd77"), "cname" : "Note Book", "pname1" : "Asus EP121 M50" } { "_id" : ObjectId("4fc23aca3153207db00dfd78"), "cname" : "Tablet", "pname1" : "Asus EP121 M50", "pname2" : "ipad3" } { "_id" : ObjectId("4fc23aca3153207db00dfd79"), "cname" : "SlatePC", "pname1" : "Asus EP121 M50", "pname2" : "Samsung eslate 7" } > db.product.find() { "_id id" : ObjectId("4fc23adc3153207db00dfd7a") ), "pname : "Asus EP121 M50, "cname1" : "Note Book", "cname2" : "Tablet", "cname3" : "SlatePC } {" "_id" id":objectid("4fc23adc3153207db00dfd7b") ObjectId("4fc23adc3153207db00dfd7b"), "pname" : "Samsung eslate 7, "cname1" : "SlatePC",} { "_id" : ObjectId("4fc23adc3153207db00dfd7c"), "pname"" : "ipad3, "cname1" : "Tablet } 58
3) Inheritence (OODBMS) Engine Frame Tire CAR 상속 (Inheritance) Engine Frame Tire Auto-Door BUS TAXI Engine Frame Tire Lamp Gas_Tank CREATE TYPE car AS OBJECT (engine NUMBER(9) Primary Key, frame VARCHAR(30), tire VARCHAR(30)) NOT FINAL; CREATE TYPE bus UNDER car_typ (auto_door VARCHAR(30) FINAL; CREATE TYPE taxi UNDER car_typ (lamp VARCHAR(30), gas_tank VARCHAR(30) FINAL; 59
Single Table Inheritence (MongoDB) > db.createcollection ( car ); > db.car.insert({ engine : A, frame : AX_1, tire : R16, car_type : TAXI, lamp : 1, gas_tank : 1}); > db.car.insert({ engine : B, frame : AK_3, tire : R18, car_type : BUS, auto_door: 2 }); > db.car.insert({ engine : A, frame : AX_ 2, tire : R18, car_type : TAXI, lamp : 2, gas_tank : 2 }); > db.car.find(); {"_id" : ObjectId("4f00574f81a153d6857897d2"), engine" : A, "ename" : AX_1, tire : R16, car_type : TAXI, lamp : 1, gas_tank : 1 }); } Engine: Frame: Tire: Car_type: Lamp: Gas_tank: A AX_1 R16 TAXI 1 1 Engine: B Engine: A Frame: AK_3 Frame: AX_1 Tire: R18 Tire: R18 Car_type: BUS Car_type: TAXI Auto_door: 1 Lamp: 2 Gas_tank: 2 60
4) 계층형데이터구조 KING Empno=7839 Empno=7782 CLARK JONES BLAKE MILLER SCOTT FORD ALLEN WARD MARTIN TURNER JAMES Empno=7934 ADAMS SMITH 61
Self Reference Join (RDBMS) Empno ename mgr b.ename ------------------------------------------------- ---------------- 7839 KING 7698 BLAKE 7839 7782 CLARK 7839 7566 JONES 7839 KING KING KING 7654 MARTIN 7698. 7902 FORD 7566 BLAKE. JONES. 7876 ADAMS 7788. JIMMY 7934 MILLER 7782 CLARK SELECT a.empno, a.ename, a.mgr, b.ename FROM emp a, emp b WHERE a.mgr = b.empno 62
Ancestor Reference (MongoDB) 7839 : KING 7782 : CLARK 7934 : MILLER > db.emp.insert({ "_id" : "7939", "name" : "KING", "job" : "PRESIDENT" }) > db.emp.insert({ "_id" : "7782", "name" : "CLARK", "job" : "ANALYSIST", "PARENT" : "7839" } ) > db.emp.insert({ "_id" : "7934", "name" : "MILLER", "job" : "CLERK", "ANCESTORS" : [ "7939", "7782" ], "PARENT" : "7782" } ) > db.emp.find({"ancestors" : "7939"}) { "_id" : "7934", "name" : "MILLER", "job" : "CLERK", "ANCESTORS" : [ "7939", "7782" ], "PARENT" : "7782" } > db.emp.find({ find({"parent" : 7839"}) { "_id" : "7782", "name" : "CLARK", "job" : "ANALYSIST", "PARENT" : "7839" } 1) 기업에서발생하는데이터구조중에는계층형데이터구조가발생할수밖에없는데이런경우적용하면가장이상적인데이터모델이다. 2) ANCESTORS 와 PARENT Field 로표현할수있으며하나의 Document 는하나이상의 ANCESTORS 와 PARENT 를가질필요는없다. 63
NoSQL 전문가가되기위해준비해야할일 1) 새로운패러다임은하루아침에변하지않는다. - 정보시스템의과거와현재를명확히직시하고미래를준비하라. 2) NoSQL 은새로운기술이아니라새로운변화다. - NoSQL 은 RDB 의문제점을개선하고 Cloud Computing 패러다임을 위한새로운 Solution 이다. 3) NOSQL 전문가가목표가아니라 DB 전문가가목표가되어야한다. - DB 개발자, DBA, DB 분석 / 설계자는 DB 전문가가되기위한과정이다. 4) 전문가가되기위해서는 DBMS 기술보다 Data 를이해하고사랑하라. - DBMS 의핵심은 Data 를잘저장관리하고활용하기위한것이다. 5) 기술을구현하는것이중요한것이아니라얼마나정확히알고제대로 사용할수있느냐이다. - 체계적인학습과실무경험이반드시필요하다. 64
Who am I?. PLAN 정보기술대표컨설턴트 - www.plandb.co.kr - jina6678@paran.com/010-3864-1858 - DB 판매 / 유지보수 / 튜닝 / 설계 / 교육 / 컨설팅. MongoDB 공식한국사용자그룹운영 - www.mongodb-korea.org g - www.mongodb-korea.co.kr. 미국 10gen co. 한국공식파트너 65