노력과 삽질 퇴적물

NoSql: MongoDB 기초 본문

프로그래밍note/미분류.

NoSql: MongoDB 기초

MTG 2019. 7. 28. 22:15





1. 기초+이론


1) 특징

> JSON형태 구조(DOCUMENT)

> 데이터 입력시, objectId라는 필드가 자동생성되며 해당 컬럼에는 중복되지 않는 유일한 값이 들어간다.

: [_id]라는 필드로 존재하고, 12바이트짜리 16진수.

예. ObjectId(5d3d8f39f450a8969574d2e1) [16]

    1글자->1바이트(8비트)

               2진수 8칸(?)->16진수 2칸(?)이므로

5d3d8f39[16]

 f450a8[16]

 9695[16]

 74d2e1[16]

 타임스탬프, 4바이트

 머신 ID, 3바이트

 DB서버 Pid, 2바이트

 순차번호, 3바이트

> db에 입력되는 DOCUMENT 그룹을 collection이라고 부름.

: 동일한 collection에 다수의 데이터 입력가능.

> NoSQL이여서 불필요한 Join 최소화 가능+고정된 스키마X.






2. 설치


1) 필요한 파일

파일명

예시 경로

 MongoDB Community Server [#4.0.11]

 D:\dev_lib\mongodb4



2) 환경변수


3) 실행

-> 서비스 등록없이 예제 테스트만 하려는 목적이라 수동 실행입니다.

-> 총 2개의 프롬프트 창을 띄우게 됩니다.

D:\dev_lib\mongodb4\save 경로로 폴더 생성후 DB 저장 경로 지정+실행

1
2
3
4
5
6
7
8
9
10
11
12
13
D:\dev_lib\mongodb4\bin>mongod --dbpath "D:\dev_lib\mongodb4\save"
2019-07-28T20:48:03.680+0900 I CONTROL  [main] Automatically disabling TLS 1.0, to force-enable TLS 1.0 specify --sslDisabledProtocols 'none'
2019-07-28T20:48:03.683+0900 I CONTROL  [initandlisten] MongoDB starting : pid=13340 port=27017 dbpath=D:\dev_lib\mongodb4\save 64-bit host=ANALOG-GREEN
2019-07-28T20:48:03.683+0900 I CONTROL  [initandlisten] targetMinOS: Windows 7/Windows Server 2008 R2
2019-07-28T20:48:03.684+0900 I CONTROL  [initandlisten] db version v4.0.11
... ... ...
2019-07-28T20:48:03.686+0900 I CONTROL  [initandlisten] options: { storage: { dbPath: "D:\dev_lib\mongodb4\save" } }
... ... ...
2019-07-28T20:48:04.982+0900 I FTDC     [initandlisten] Initializing full-time diagnostic data capture with directory 'D:/dev_lib/mongodb4/save/diagnostic.data'
... ... ...
2019-07-28T20:48:05.338+0900 I INDEX    [LogicalSessionCacheRefresh]     building index using bulk method; build may temporarily use up to 500 megabytes of RAM
2019-07-28T20:48:05.346+0900 I INDEX    [LogicalSessionCacheRefresh] build index done.  scanned 0 total records. 0 secs
2019-07-28T20:48:05.346+0900 I COMMAND  [LogicalSessionCacheRefresh] command config.$cmd command: createIndexes { createIndexes: "system.sessions", indexes: [ { key: { lastUse: 1 }, name: "lsidTTLIndex", expireAfterSeconds: 1800 } ], $db: "config" } numYields:0 reslen:114 locks:{ Global: { acquireCount: { r: 2, w: 2 } }, Database: { acquireCount: { w: 2, W: 1 } }, Collection: { acquireCount: { w: 2 } } } storage:{} protocol:op_msg 361ms
cs


제 경우, [http://localhost:27017]로 접속시
[It looks like you are trying to access MongoDB over HTTP on the native driver port.]

라는 메시지가 브라우저에 출력됩니다.

프롬프트 창을 1개 더 띄워고서

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
D:\dev_lib\mongodb4\bin>mongo
MongoDB shell version v4.0.11
connecting to: mongodb://127.0.0.1:27017/?gssapiServiceName=mongodb
... ... ...
MongoDB server version: 4.0.11
Server has startup warnings:
2019-07-28T20:53:20.267+0900 I CONTROL  [initandlisten]
2019-07-28T20:53:20.267+0900 I CONTROL  [initandlisten] ** WARNING: Access control is not enabled for the database.
2019-07-28T20:53:20.267+0900 I CONTROL  [initandlisten] **          Read and write access to data and configuration is unrestricted.
2019-07-28T20:53:20.267+0900 I CONTROL  [initandlisten]
2019-07-28T20:53:20.268+0900 I CONTROL  [initandlisten] ** WARNING: This server is bound to localhost.
2019-07-28T20:53:20.268+0900 I CONTROL  [initandlisten] **          Remote systems will be unable to connect to this server.
2019-07-28T20:53:20.268+0900 I CONTROL  [initandlisten] **          Start the server with --bind_ip <address> to specify which IP
2019-07-28T20:53:20.268+0900 I CONTROL  [initandlisten] **          addresses it should serve responses from, or with --bind_ip_all to
2019-07-28T20:53:20.268+0900 I CONTROL  [initandlisten] **          bind to all interfaces. If this behavior is desired, start the
2019-07-28T20:53:20.268+0900 I CONTROL  [initandlisten] **          server with --bind_ip 127.0.0.1 to disable this warning.
2019-07-28T20:53:20.268+0900 I CONTROL  [initandlisten]
---
Enable MongoDB's free cloud-based monitoring service, which will then receive and display
metrics about your deployment (disk utilization, CPU, operation statistics, etc).
The monitoring data will be available on a MongoDB website with a unique URL accessible to you
and anyone you share the URL with. MongoDB may use this information to make product
improvements and to suggest MongoDB products and deployment options to you.
To enable free monitoring, run the following command: db.enableFreeMonitoring()
To permanently disable this reminder, run the following command: db.disableFreeMonitoring()
---
>
cs






4. 예제


1) 기본 명령어

1
2
3
4
5
6
7
8
9
10
11
// INSERT.
> db.sampleCollec.insert(
... {
... date:"2019-07-28",
... writer:"MuTeukGi",
... title:"sample insert"
... }
... )
WriteResult({ "nInserted" : 1 })
> db.sampleCollec.find()
"_id" : ObjectId("5d3d8f39f450a8969574d2e1"), "date" : "2019-07-28""writer" : "MuTeukGi""title" : "sample insert" }
cs


1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
// UPDATE.
> db.sampleCollec.insert(
... {
... date:"2019-07-28",
... writer:"MuTeukGi",
... title:"sample 2",
... tag:"data 2"
... }
... )
WriteResult({ "nInserted" : 1 })
> db.sampleCollec.find()
"_id" : ObjectId("5d3d8f39f450a8969574d2e1"), "date" : "2019-07-28""writer" : "MuTeukGi""title" : "sample insert" }
"_id" : ObjectId("5d3d9325f450a8969574d2e2"), "date" : "2019-07-28""writer" : "MuTeukGi""title" : "sample 2""tag" : "data 2" }
> db.sampleCollec.update(
... {title:"sample 2"},  //조건문.(in SQL, where)
... {$set: {ver:1}} //update 쿼리문
... )
WriteResult({ "nMatched" : 1"nUpserted" : 0"nModified" : 1 })
> db.sampleCollec.find()
"_id" : ObjectId("5d3d8f39f450a8969574d2e1"), "date" : "2019-07-28""writer" : "MuTeukGi""title" : "sample insert" }
"_id" : ObjectId("5d3d9325f450a8969574d2e2"), "date" : "2019-07-28""writer" : "MuTeukGi""title" : "sample 2""tag" : "data 2""ver" : 1 }
cs


dynamoDB와 달리 update시, 조건문을 이용해서 N개의 아이템에서 특정 컬럼값만 수정되게 지정이 가능하고,

$set, $pull등 특정 컬럼값 수정에 대한 처리가 가능.






기타. 참조자료


01. MongoDB(몽고디비) Study - NoSQL 이란? 그리고 MongoDB 소개

[MongoDB] 강좌 1편: 소개, 설치 및 데이터 모델링 | VELOPERT.LOG


조대협의 블로그 :: MongoDB 30분만에 이해하기.. (설치,테스트 및 자바 샘플)

[mongoDB] mongoDB 설치하기 / 환경설정 - windows - DWFOX

몽고디비 윈도우 설치 (zip 파일) : 네이버 블로그


MongoDB CRUD Operations — MongoDB Manual

[MongoDB] 강좌 5편 Document 수정 – update() 메소드 | VELOPERT.LOG






기타. 변경이력


일자

변경이력

2019-07-28

 초안.