들어가며..
시작에 앞서 현재 포스팅은 MongoDB 5.0 버전의 document의 내용을 요약 정리한 것임을 밝힙니다.
오류나 잘못 이해하여 정리한 부분에 대한 지적은 언제나 환영합니다.
개요
몽고 디비는 development와 scaling (특히 수평적 확장)이 용이하도록 설계된 document base database로서, 공식 문서에서 소개하는 몽고 디비의 핵심 컨셉은 다음과 같다.
- query API
- Operational and administrative references
- Tutorials and procedures
몽고디비 버전 정보
몽고 디비는 로컬과 클라우드에서 모두 배포 및 사용이 가능한데
로컬에서는 커뮤니티 버전과 엔터프라이즈 버전 모두 사용이 가능하고
클라우드 환경 (MongoDB Atlas) 에서는 엔터프라이즈 버전을 제공한다.
커뮤니티 버전과 엔터프라이즈 버전의 차이?
커뮤니티 버전
- 무료로 사용 가능한 버전
엔터프라이즈 버전
- 엔터프라이즈 구독을 통해 사용가능하고, 추가적인 기능 / LDAP, Kerberos 지원 등을 제공 받을 수 있다.
몽고 디비 라이센스
Server Side Public License FAQ
Server Side Public License FAQ
What specifically is the difference between the GPL and the SSPL? The only substantive modification is section 13, which makes clear the condition to offering MongoDB as a service. A company that offers a publicly available MongoDB as a service must releas
www.mongodb.com
몽고디비는 SSPL 라이센스를 채택하고 있으며 이는 일반적인 오픈소스 라이센스와 다른 점이 존재하기 때문에 상세한 정보를 찾아보는 것을 추천함
Document Database
몽고비비와 MySQL 비교
MongoDB Vs MySQL
We compare MongoDB & MySQL's performance, speed, and scalability
www.mongodb.com
몽고 디비의 record는 field와 value의 쌍으로 이루어진 구조를 가지고 있다.
이것은 json과 유사한 키-값 형태로 볼 수 있고, 각 field의 value로는
또 다른 document, array, array of document 등을 가질 수 있다.
이러한 document 구조가 가지는 장점은 다음과 같다.
- 많은 프로그래밍 언어에서 document type을 기본적으로 보유하고 있음 (native data type)
- document와 array의 중첩이 가능하기 때문에 join 연산에 들어가는 비용을 절약할 수 있음
→ 그에 따라 ACID 속성은 포기해야하긴 하지만 이것이 중요치 않다면 괜찮겠지? - 스키마리스 : 다형성이 보장된다
→ 다형성 : 여러 형태를 받아들일 수 있는 성질로, 상황에 따라 다른 data type을 동적으로 할당 가능
Collections/Views/On-Demand Materialized Views
몽고디비는 document를 collection이라는 단위에 저장하게 된다.
이 collection은 RDB에서의 테이블과 유사한 개념으로 볼 수 있다.
또한 다음과 같은 기능들도 제공한다.
- Read-only Views (Starting in MongoDB 3.4)
- On-Demand Materialized Views (Starting in MongoDB 4.2).
핵심 기능 Key Features
High Performance
몽고 디비는 고성능의 데이터 지속성 (data persistense)를 제공한다.
- 중첩 구조로 DB의 I/O 를 감소
- 인덱스를 통해 더 빠른 쿼리 속도를 제공하고 중첩 데이터에 대한 키를 제공
Query API
몽고 디비에서의 CRUD 수행을 위한 쿼리 제공
High Availability (고가용성)
레플리카 (복제) 기능을 통해
- 데이터 자동 복구
- 데이터 중복 저장
기능을 제공하여 고가용성 보장
Horizonatl Sacalability (수평 확장성)
수평 확장성 (스케일 아웃) 기능을 제공
- Sharding을 통해 데이터를 시스템 클러스터 전체에 분산 저장
- 3.4 버전부터 shard key를 기반으로 data zones을 생성하는 기능을 제공
- 균형잡힌 클러스터 구조에서 몽고 디비는 데이터를 읽고 쓰는 연산을 샤드가 포함된 zone으로 유도하고 좀 더 효율적인 연산 수행이 가능하게 함
Multiple Storage Engines
여러가지 저장 엔진에 대한 기능을 지원함
- WiredTiger Storage Engine (including support for Encryption at Rest)
- In-Memory Storage Engine.
→ 추가적으로 몽고디비용 storage engine을 개발 할 수 있는 API를 제공하고 있음
MongoDB 기본 쿼리 실습
실습 환경
https://www.mongodb.com/docs/manual/tutorial/getting-started/
Getting Started — MongoDB Manual
Docs Home → MongoDB ManualThis tutorial walks you through inserting test data into a MongoDB database and querying that data using the documentation's embedded web shell. You do not need to deploy or install MongoDB to complete this tutorial.The examples
www.mongodb.com
1. Switch Database
현재 사용중인 데이터베이스 정보 출력
db
사용할 데이터베이스 선택
# 해당 데이터베이스가 없는 경우 생성하고, 전환
use examples
2. Insert
몽고 디비는 document를 collection이라는 단위에 저장한다.
이 collection은 RDB에서의 table과 유사한 개념으로 앞선 데이터베이스와 마찬가지로
관련 명령어를 실행했을때 해당 collection이 존재하지 않는다면 자동으로 생성하고 데이터 삽입 등의 연산을 수행한다.
다음은 movies 라는 collection 안에 document를 insert하는 query이다.
db.movies.insertMany([
{
title: 'Titanic',
year: 1997,
genres: [ 'Drama', 'Romance' ],
rated: 'PG-13',
languages: [ 'English', 'French', 'German', 'Swedish', 'Italian', 'Russian' ],
released: ISODate("1997-12-19T00:00:00.000Z"),
awards: {
wins: 127,
nominations: 63,
text: 'Won 11 Oscars. Another 116 wins & 63 nominations.'
},
cast: [ 'Leonardo DiCaprio', 'Kate Winslet', 'Billy Zane', 'Kathy Bates' ],
directors: [ 'James Cameron' ]
},
{
title: 'The Dark Knight',
year: 2008,
genres: [ 'Action', 'Crime', 'Drama' ],
rated: 'PG-13',
languages: [ 'English', 'Mandarin' ],
released: ISODate("2008-07-18T00:00:00.000Z"),
awards: {
wins: 144,
nominations: 106,
text: 'Won 2 Oscars. Another 142 wins & 106 nominations.'
},
cast: [ 'Christian Bale', 'Heath Ledger', 'Aaron Eckhart', 'Michael Caine' ],
directors: [ 'Christopher Nolan' ]
},
{
title: 'Spirited Away',
year: 2001,
genres: [ 'Animation', 'Adventure', 'Family' ],
rated: 'PG',
languages: [ 'Japanese' ],
released: ISODate("2003-03-28T00:00:00.000Z"),
awards: {
wins: 52,
nominations: 22,
text: 'Won 1 Oscar. Another 51 wins & 22 nominations.'
},
cast: [ 'Rumi Hiiragi', 'Miyu Irino', 'Mari Natsuki', 'Takashi Naitè' ],
directors: [ 'Hayao Miyazaki' ]
},
{
title: 'Casablanca',
genres: [ 'Drama', 'Romance', 'War' ],
rated: 'PG',
cast: [ 'Humphrey Bogart', 'Ingrid Bergman', 'Paul Henreid', 'Claude Rains' ],
languages: [ 'English', 'French', 'German', 'Italian' ],
released: ISODate("1943-01-23T00:00:00.000Z"),
directors: [ 'Michael Curtiz' ],
awards: {
wins: 9,
nominations: 6,
text: 'Won 3 Oscars. Another 6 wins & 6 nominations.'
},
lastupdated: '2015-09-04 00:22:54.600000000',
year: 1942
}
])
3. Find ALL
collection 안에 있는 document를 조회하기 위해서는
db.collection.find() 메서드를 사용하면 된다.
이때 별다른 조건 없이 모든 document를 조회하려면
db.movies.find( { } )와 같이 빈 document를 전달하여 실행하면 된다.
4. Filter Data
비교 연산자를 통해 데이터를 필터링 하는 것이 가능하다.
앞선 db.collection.find() 메서드 내부에 특정 필드의 특정 값을 구체적으로 명시한다면
해당 조건에 부합하는 document만 조회하여 확인 할 수 있다.
db.movies.find( { **"directors"**: **"Christopher Nolan"** } );
→ 감독이 크리스토퍼 놀란인 영화 정보만 조회
비교 연산자를 통해 좀 더 복잡한 기능을 하는 advanced query를 사용할 수 있다.
You can use comparison operators to perform more advanced queries:
- 2000 이전에 개봉한 영화 정보 조회
- db.movies.find( {"released": { $lt: ISODate("2000-01-01") } } );
- 100 개 이상의 상을 받은 영화 정보 조회
- db.movies.find( {"awards.wins": { $gt: 100 } } );
- languages 필드 안의 배열에 Japanese 혹은 Mandarin이 존재하는 경우 영화 정보 조회
- db.movies.find( {"languages": { $in: ["Japanese","Mandarin" ] } } )
5. Project Fields
반환할 필드 정보를 지정하기 위해서는 db.collection.find() 메서드 안에
projection document를 추가해야한다.
db.collection.find(<query document>, <projection documenmt>)
이때 반활할 피드 정보를 0, 1을 설정해 조작이 가능한데
- <field>: 1 설정된 필드를 반환 값으로 사용
- <field>: 0 선정되지 않은 모든 필드를 제외하도록 설정
db.movies.find( { }, { **"title"**: 1, **"directors"**: 1, **"year"**: 1 } );
db.movies.find( { }, { **"_id"**: 0, **"title"**: 1, **"genres"**: 1 } );
6. Aggregate
몽고 디비에서 aggregation은 aggregation pipelione을 통해 사용 가능하다.
db.movies.aggregate( [
{ $unwind: "$genres" },
{
$group: {
_id: "$genres",
genreCount: { $count: { } }
}
},
{ $sort: { "genreCount": -1 } }
] )
※이 포스팅은 MongoDB 5.0 버전 기반으로 작성되었으며, 참고한 공식 Document 또한 동일 버전입니다.
'Data Engineering' 카테고리의 다른 글
MongoDB 5.X - illegal instruction (core dumped) 이슈 (0) | 2022.06.26 |
---|---|
Grafana Migration (sqlite3 to MySQL) (2) | 2022.05.27 |
2.1.3 엘라스틱 서치 구성 요소 및 구조 (인덱스/샤드/세그먼트) (0) | 2022.02.14 |
맥에서 하둡 설치하기 (1) | 2021.11.15 |
2.1.2 엘라스틱 서치의 구성 요소 및 구조 (노드) (0) | 2021.11.02 |