자바스크립트 셸을 통한 mongoDB
- MongoDB 셸은 데이터베이스를 테스트하고, 애드훅 쿼리를 실행하고, MongoDB 인스턴스 관리를 수행하기 위해 사용하는 도구.
- 셸을 통해 데이터를 검사하고 조작할 수 있으며, 데이터베이스 서버 자체를 관리 가능.
- SQL과 같이 표준화된 쿼리 언어를 사용하는 것과 달르게 자바스크립트 프로그래밍 언어와 간단한 API를 사용해 서버와 연결.
- 사용자가 다양한 목적으로 자신의 스크립트를 만들고 로드할 수 있는 완전한 기능의 자바스크립트 해석기.
1. MongoDB 셸 경험하기
1.1 셸 시작하기
MongoDB 설치 후 mongo 실행 파일을 실행하여 MongoDB 셸 시작하기
mongo
>
1.2 데이터베이스, 컬렉션, 도큐먼트
1.2.1 도큐먼트
- 정렬된 키와 연결된 값의 집합
- 키는 문자열 몇가지 예외를 제외한 어떤 UTF-8 문자 사용 가능하며 대소문자 구분 및 중복 될 수 없음
(null문자 포함 X, .과 $는 예약어로 사용 X)
- 관계형 데이터베이스의 행에 대응
1.2.2 컬렉션
- 도큐먼트의 모음
- 관계형 데이터베이스의 테이블에 대응
- 동적 스키마를 가지기에 컬렉션 내 도큐먼트들이 모두 다른 구조를 가질 수 있음
- 이름으로 식별되며 몇가지 예외를 제외한 어떤 UTF-8 문자 사용 가능
(null문자 포함 X, System.으로 시작하는 컬렉션명은 시스템 컬렉션으로 사용 X, 사용자가 만든 컬렉션에는 .과 $는 예약어로 사용 X)
- 네임스페이스에 . 문자를 사용하여 서브컬렉션을 구성하여 컬렉션을 체계화 가능
(blog.posts, blog.authors 등)
1.2.3 데이터베이스
- 데이터베이스에 컬렉션을 그룹 지어 사용
- 컬렉션과 마찬가지로 이름으로 식별되며 몇가지 예외를 제외한 어떤 UTF-8 문자 사용 가능
(빈 문자열, /, \, ., ' ', <, >, :, |, ?, $, (단일 공간), \0(null문자) 사용 X)
- 이름은 대소문자 구분 및 최대 64바이트
1.3 삽입과 질의
- 삽입 작업은 단일 컬렉션을 대상
- 모든 쓰기 작업은 단일 도큐먼트 수준에서 원자적
# 도큐먼트 삽입
db.collection.insertOne()
- 3.2 버전의 새로운 기능
- 단일 도큐먼트에 대해 컬렉션에 삽입
db.collection.insertOne(
<document>,
{
writeConcern: <document>
}
)
document
- 컬렉션에 삽입할 도큐먼트
writeConcern
- 선택 옵션.
- insertOne, insertMany 등의 명령어를 통해 도큐먼트를 컬렉션에 넣으려고 할 때 해당 컬렉션이 쓰기작업(도큐먼트 생성, 수정, 삭제) 중이라면 어떻게 할 것인지에 대한 것.
db.collection.insertMany()
- 3.2 버전의 새로운 기능
- 여러 도큐먼트를 컬렉션에 삽입
db.collection.insertMany(
[ <document 1> , <document 2>, ... ],
{
writeConcern: <document>,
ordered: <boolean>
}
)
document
- 컬렉션에 삽입할 도큐먼트의 배열
writeConcern
- 선택 옵션.
- insertOne, insertMany 등의 명령어를 통해 도큐먼트를 컬렉션에 넣으려고 할 때 해당 컬렉션이 쓰기작업(도큐먼트 생성, 수정, 삭제) 중이라면 어떻게 할 것인지에 대한 것.
ordered
- 선택 옵션으로 기본값은 true
- mongod 인스턴스가 순서가 지정된 삽입 또는 순서 없는 삽입을 수행해야 하는지 여부를 지정하는 값
db.collection.bulkWrite()
- 대량 도큐먼트 등록에 사용
# 도큐먼트 질의
db.collection.find(query, projection)
query
- 선택 옵션.
- 쿼리 연산자를 사용하여 선택 필터를 지정.
- 컬렉션의 모든 도큐먼트를 반환하려면 이 매개변수를 생략하거나 빈 문서({})를 전달
projection
- 선택 옵션.
- 쿼리 필터와 일치하는 문서에서 반환할 필드를 지정.
1.4 도큐먼트 업데이트
# 갱신
- 업데이트 작업은 컬렉션의 기존 도큐먼트를 갱신
db.collection.updateOne(filter, update, options)
- 3.2 버전의 새로운 기능
db.collection.updateMany(filter, update, options)
- 3.2 버전의 새로운 기능
db.collection.replaceOne(filter, replacement, options)
- 3.2 버전의 새로운 기능
1.5 도큐먼트 삭제
# 삭제
- 삭제 작업은 컬렉션에서 도큐먼트를 삭제
db.collection.deleteOne()
db.collection.deleteOne(
<filter>,
{
writeConcern: <document>,
collation: <document>,
hint: <document|string> // Available starting in MongoDB 4.4
}
)
db.collection.deleteMany()
db.collection.deleteMany(
<filter>,
{
writeConcern: <document>,
collation: <document>
}
)
전체 도큐먼트 삭제
- deleteMany를 사용해도 가능하지만 drop을 사용하는 것이 더 빠름
2. 인덱스 생성과 질의
2.1 대용량 컬렉션 생성
인덱싱 예제 데이터 추가
for(i = 0; i < 20000; i++) {
db.numbers.save({num: i});
}
범위 쿼리
> db.numbers.find({num: {"$gt": 19995}})
{ "_id" : ObjectId("615502771f1576a465ee14ec"), "num" : 19996 }
{ "_id" : ObjectId("615502771f1576a465ee14ed"), "num" : 19997 }
{ "_id" : ObjectId("615502771f1576a465ee14ee"), "num" : 19998 }
{ "_id" : ObjectId("615502771f1576a465ee14ef"), "num" : 19999 }
> db.numbers.find({num: {"$gt": 20, "$lt": 25}})
{ "_id" : ObjectId("615502691f1576a465edc6e5"), "num" : 21 }
{ "_id" : ObjectId("615502691f1576a465edc6e6"), "num" : 22 }
{ "_id" : ObjectId("615502691f1576a465edc6e7"), "num" : 23 }
{ "_id" : ObjectId("615502691f1576a465edc6e8"), "num" : 24 }
2.2 인덱싱과 explain
explain()
- 쿼리 실행 계획 확인
- explain.executionStats.totalDocsExamined: 쿼리 실행 중에 검사된 문서 수
> db.numbers.find({num: {"$gt": 19995}}).explain("executionStats")
{
"explainVersion" : "1",
"queryPlanner" : {
"namespace" : "tutorial.numbers",
"indexFilterSet" : false,
"parsedQuery" : {
"num" : {
"$gt" : 19995
}
},
"maxIndexedOrSolutionsReached" : false,
"maxIndexedAndSolutionsReached" : false,
"maxScansToExplodeReached" : false,
"winningPlan" : {
"stage" : "COLLSCAN",
"filter" : {
"num" : {
"$gt" : 19995
}
},
"direction" : "forward"
},
"rejectedPlans" : [ ]
},
"executionStats" : {
"executionSuccess" : true,
"nReturned" : 4,
"executionTimeMillis" : 27,
"totalKeysExamined" : 0,
"totalDocsExamined" : 20000,
"executionStages" : {
"stage" : "COLLSCAN",
"filter" : {
"num" : {
"$gt" : 19995
}
},
"nReturned" : 4,
"executionTimeMillisEstimate" : 3,
"works" : 20002,
"advanced" : 4,
"needTime" : 19997,
"needYield" : 0,
"saveState" : 20,
"restoreState" : 20,
"isEOF" : 1,
"direction" : "forward",
"docsExamined" : 20000
}
},
"command" : {
"find" : "numbers",
"filter" : {
"num" : {
"$gt" : 19995
}
},
"$db" : "tutorial"
},
"serverInfo" : {
"host" : "DESKTOP-KV5186R",
"port" : 27017,
"version" : "5.0.3",
"gitVersion" : "657fea5a61a74d7a79df7aff8e4bcf0bc742b748"
},
"serverParameters" : {
"internalQueryFacetBufferSizeBytes" : 104857600,
"internalQueryFacetMaxOutputDocSizeBytes" : 104857600,
"internalLookupStageIntermediateDocumentMaxSizeBytes" : 104857600,
"internalDocumentSourceGroupMaxMemoryBytes" : 104857600,
"internalQueryMaxBlockingSortMemoryUsageBytes" : 104857600,
"internalQueryProhibitBlockingMergeOnMongoS" : 0,
"internalQueryMaxAddToSetBytes" : 104857600,
"internalDocumentSourceSetWindowFieldsMaxMemoryBytes" : 104857600
},
"ok" : 1
}
인덱스 생성
- db.numbers.createIndex
> db.numbers.createIndex({num: 1})
{
"numIndexesBefore" : 1,
"numIndexesAfter" : 2,
"createdCollectionAutomatically" : false,
"ok" : 1
}
인덱스 생성 후
> db.numbers.find({num: {"$gt": 19995}}).explain("executionStats")
{
"explainVersion" : "1",
"queryPlanner" : {
"namespace" : "tutorial.numbers",
"indexFilterSet" : false,
"parsedQuery" : {
"num" : {
"$gt" : 19995
}
},
"maxIndexedOrSolutionsReached" : false,
"maxIndexedAndSolutionsReached" : false,
"maxScansToExplodeReached" : false,
"winningPlan" : {
"stage" : "FETCH",
"inputStage" : {
"stage" : "IXSCAN",
"keyPattern" : {
"num" : 1
},
"indexName" : "num_1",
"isMultiKey" : false,
"multiKeyPaths" : {
"num" : [ ]
},
"isUnique" : false,
"isSparse" : false,
"isPartial" : false,
"indexVersion" : 2,
"direction" : "forward",
"indexBounds" : {
"num" : [
"(19995.0, inf.0]"
]
}
}
},
"rejectedPlans" : [ ]
},
"executionStats" : {
"executionSuccess" : true,
"nReturned" : 4,
"executionTimeMillis" : 1,
"totalKeysExamined" : 4,
"totalDocsExamined" : 4,
"executionStages" : {
"stage" : "FETCH",
"nReturned" : 4,
"executionTimeMillisEstimate" : 0,
"works" : 5,
"advanced" : 4,
"needTime" : 0,
"needYield" : 0,
"saveState" : 0,
"restoreState" : 0,
"isEOF" : 1,
"docsExamined" : 4,
"alreadyHasObj" : 0,
"inputStage" : {
"stage" : "IXSCAN",
"nReturned" : 4,
"executionTimeMillisEstimate" : 0,
"works" : 5,
"advanced" : 4,
"needTime" : 0,
"needYield" : 0,
"saveState" : 0,
"restoreState" : 0,
"isEOF" : 1,
"keyPattern" : {
"num" : 1
},
"indexName" : "num_1",
"isMultiKey" : false,
"multiKeyPaths" : {
"num" : [ ]
},
"isUnique" : false,
"isSparse" : false,
"isPartial" : false,
"indexVersion" : 2,
"direction" : "forward",
"indexBounds" : {
"num" : [
"(19995.0, inf.0]"
]
},
"keysExamined" : 4,
"seeks" : 1,
"dupsTested" : 0,
"dupsDropped" : 0
}
}
},
"command" : {
"find" : "numbers",
"filter" : {
"num" : {
"$gt" : 19995
}
},
"$db" : "tutorial"
},
"serverInfo" : {
"host" : "DESKTOP-KV5186R",
"port" : 27017,
"version" : "5.0.3",
"gitVersion" : "657fea5a61a74d7a79df7aff8e4bcf0bc742b748"
},
"serverParameters" : {
"internalQueryFacetBufferSizeBytes" : 104857600,
"internalQueryFacetMaxOutputDocSizeBytes" : 104857600,
"internalLookupStageIntermediateDocumentMaxSizeBytes" : 104857600,
"internalDocumentSourceGroupMaxMemoryBytes" : 104857600,
"internalQueryMaxBlockingSortMemoryUsageBytes" : 104857600,
"internalQueryProhibitBlockingMergeOnMongoS" : 0,
"internalQueryMaxAddToSetBytes" : 104857600,
"internalDocumentSourceSetWindowFieldsMaxMemoryBytes" : 104857600
},
"ok" : 1
}
조회에 걸린 시간과 검사된 문서 수가 줄어든 것을 확인할 수 있음
인덱스 확인
- db.collection.getIndexes()
> db.numbers.getIndexes()
[
{
"v" : 2,
"key" : {
"_id" : 1
},
"name" : "_id_" // 컬렉션 생성 시 자동 생성되는 표준 인덱스
},
{
"v" : 2,
"key" : {
"num" : 1
},
"name" : "num_1" // 사용자가 추가한 인덱스
}
]
3. 기본적인 관리
3.1 데이터베이스 정보 얻기
show dbs
- 시스템상의 모든 데이터베이스 정보 조회
show collections
- 현재 사용 중인 데이터베이스에서 정의된 모든 컬렉션 정보 조회
db.stats() 또는 db.{collection}.stats()
- 데이터베이스와 컬렉션에 대해 좀 더 하위 계층 정보에 대한 조회
** 내용 추가 중입니다 **
'dev > DB' 카테고리의 다른 글
| MongoDB - 집계1 (0) | 2021.10.28 |
|---|---|
| MongoDB - Query Selectors(1) (0) | 2021.10.22 |
| [MongoDB] 도큐먼트 지향 데이터 (0) | 2021.10.15 |
| MongoDB 핵심 기능 요약 (0) | 2021.09.27 |
| MongoDB 설치 (0) | 2020.07.27 |