몽고디비 인 액션 2장

자바스크립트 셸을 통한 MongoDB

다른 툴과 다른 점은 쿼리 언어에 있다. SQL과 같이 표준화된 쿼리 언어를 사용하는 것 대신에 자바스크립트 프로그래밍 언어와 간단한 API를 사용해 서버와 연결한다.

MongoDB설치(부록A)

윈도우 설치

https://www.mongodb.com/try/download/community

원도우 명령프롬프트(커맨드창)에서도 명령어로 접속이 가능하도록 Path를 설정
제어판 > 환경변수 > 시스템Path > 몽고디비설치 bin경로 추가 (C:\Program Files\MongoDB\Server\5.0\bin)

>mongo
MongoDB shell version v5.0.3
connecting to: mongodb://127.0.0.1:27017/?compressors=disabled&gssapiServiceName=mongodb
Implicit session: session { "id" : UUID("ac3b57dd-3cfb-4e30-8bf1-e670a291f133") }
MongoDB server version: 5.0.3
================
Warning: the "mongo" shell has been superseded by "mongosh",
which delivers improved usability and compatibility.The "mongo" shell has been deprecated and will be removed in
an upcoming release.
We recommend you begin using "mongosh".
For installation instructions, see
https://docs.mongodb.com/mongodb-shell/install/
================
Welcome to the MongoDB shell.
...
> use testdb
switched to db testdb

데이터베이스, 컬렉션, 도큐먼트

MongoDB가 RDBMS의 테이블과 같이 도큐먼트들을 grouping하는 것을 컬렉션(collection)이라 부른다.
=> 사용자(user) / 주문(order)

MongoDB는 컬렉션들을 별도의 데이터베이스(단지 컬렉션을 분리하는 네임스페이스개념)에 분리한다. 따라서 질의를 하기 원하는 대상 도큐먼트가 존재하는 데이터베이스와 컬렉션을 알아야한다.

데이터베이스변경 (아직 실제로 생성안된상태. 데이터베이스와 컬렉션은 도큐먼트가 처음 입력될 때 생성됨)

> use tutorial
switched to db tutorial

MongoDB가 데이터베이스와 컬렉션을 모두 가지고 있는 이유 : 데이터베이스의 모든 컬렉션은 같은 파일에 grouping함. 메모리 관점 및 애플리케이션에서 접근할 때 이점

삽입과 질의

> db.users.insert({username:"una"})
WriteResult({ "nInserted" : 1 })
> db.users.find()
{ "_id" : ObjectId("6154f18d7b36c03e7fbbab05"), "username" : "una" }

_id : 도큐먼트의 프라이머리 키 (삽입을 통해 _id를 지정할 수 있으며, 없을 때 자동 생성)

> db.users.insert({username:"gongu"})
WriteResult({ "nInserted" : 1 })
> db.users.count()
2

count : 컬렉션 수 counting

> db.users.insert({username:"una"})
WriteResult({ "nInserted" : 1 })
> db.users.find()
{ "_id" : ObjectId("6154f18d7b36c03e7fbbab05"), "username" : "una" }
{ "_id" : ObjectId("6154f37b7b36c03e7fbbab06"), "username" : "gongu" }
{ "_id" : ObjectId("6154f4c67b36c03e7fbbab07"), "username" : "una" }
> db.users.find({$and:[
... {_id:ObjectId("6154f18d7b36c03e7fbbab05")},
... {username:"una"}
... ]})
{ "_id" : ObjectId("6154f18d7b36c03e7fbbab05"), "username" : "una" }
> db.users.find({$or:[
... {username:"una"},
... {username:"gongu"}
... ]})
{ "_id" : ObjectId("6154f18d7b36c03e7fbbab05"), "username" : "una" }
{ "_id" : ObjectId("6154f37b7b36c03e7fbbab06"), "username" : "gongu" }
{ "_id" : ObjectId("6154f4c67b36c03e7fbbab07"), "username" : "una" }

$and : AND 연산자
$or : OR 연산자

도큐먼트 업데이트

> db.users.update({username:"gongu"},{$set:{country:"Korea"}})
WriteResult({ "nMatched" : 1, "nUpserted" : 0, "nModified" : 1 })
> db.users.find(
... {username:"gongu"})
{ "_id" : ObjectId("6154f37b7b36c03e7fbbab06"), "username" : "gongu", "country" : "Korea" }

$set : 도큐먼트를 찾아서 속성을 추가수정

> db.users.update({username:"una"},{country:"japan"})
WriteResult({ "nMatched" : 1, "nUpserted" : 0, "nModified" : 1 })
> db.users.find()
{ "_id" : ObjectId("6154f18d7b36c03e7fbbab05"), "country" : "japan" }
{ "_id" : ObjectId("6154f37b7b36c03e7fbbab06"), "username" : "gongu", "country" : "Korea" }
{ "_id" : ObjectId("6154f4c67b36c03e7fbbab07"), "username" : "una" }

필드를 추가하거나 값을 설정하기를 원한다면 반드시 $set을 사용.

> db.users.update({username:"gongu"},{$unset:{country:2}})
WriteResult({ "nMatched" : 1, "nUpserted" : 0, "nModified" : 1 })
> db.users.find()
{ "_id" : ObjectId("6154f18d7b36c03e7fbbab05"), "country" : "japan" }
{ "_id" : ObjectId("6154f37b7b36c03e7fbbab06"), "username" : "gongu" }
{ "_id" : ObjectId("6154f4c67b36c03e7fbbab07"), "username" : "una" }

$unset : 속성을 삭제

> var movies = ["m1","m2","m3"]
> var hobby = ["h1", "h2", "h3"]
> var favoriteObj = {favorites:{movies:movies, hobby:hobby}}
> favoriteObj
{
        "favorites" : {
                "movies" : [
                        "m1",
                        "m2",
                        "m3"
                ],
                "hobby" : [
                        "h1",
                        "h2",
                        "h3"
                ]
        }
}
> db.users.update({username:"gongu"},{$set:favoriteObj})
WriteResult({ "nMatched" : 1, "nUpserted" : 0, "nModified" : 1 })
> db.users.find()
{ "_id" : ObjectId("6154f18d7b36c03e7fbbab05"), "country" : "japan" }
{ "_id" : ObjectId("6154f37b7b36c03e7fbbab06"), "username" : "gongu", "favorites" : { "movies" : [ "m1", "m2", "m3" ], "hobby" : [ "h1", "h2", "h3" ] } }
{ "_id" : ObjectId("6154f4c67b36c03e7fbbab07"), "username" : "una" }
> db.users.find().pretty()
{ "_id" : ObjectId("6154f18d7b36c03e7fbbab05"), "country" : "japan" }
{
        "_id" : ObjectId("6154f37b7b36c03e7fbbab06"),
        "username" : "gongu",
        "favorites" : {
                "movies" : [
                        "m1",
                        "m2",
                        "m3"
                ],
                "hobby" : [
                        "h1",
                        "h2",
                        "h3"
                ]
        }
}
{ "_id" : ObjectId("6154f4c67b36c03e7fbbab07"), "username" : "una" }
> db.users.find({"favorites.movies":"m2"})
{ "_id" : ObjectId("6154f37b7b36c03e7fbbab06"), "username" : "gongu", "favorites" : { "movies" : [ "m1", "m2", "m3" ], "hobby" : [ "h1", "h2", "h3" ] } }

도큐먼트안의 오브젝트(favorites) 키(hobby)에 접근하기 위해선 닷(.)을 이용하여 접근한다.

> db.users.update({username:"gongu"},{$set:{"favorites.movies":["mv1"]}})
WriteResult({ "nMatched" : 1, "nUpserted" : 0, "nModified" : 1 })
> db.users.find().pretty()
{ "_id" : ObjectId("6154f18d7b36c03e7fbbab05"), "country" : "japan" }
{
        "_id" : ObjectId("6154f37b7b36c03e7fbbab06"),
        "username" : "gongu",
        "favorites" : {
                "movies" : [
                        "mv1"
                ],
                "hobby" : [
                        "h1",
                        "h2",
                        "h3"
                ]
        }
}
{ "_id" : ObjectId("6154f4c67b36c03e7fbbab07"), "username" : "una" }
> db.users.update({username:"gongu"},{$addToSet:{"favorites.movies":"mv2"}})
WriteResult({ "nMatched" : 1, "nUpserted" : 0, "nModified" : 1 })
> db.users.find().pretty()
{ "_id" : ObjectId("6154f18d7b36c03e7fbbab05"), "country" : "japan" }
{
        "_id" : ObjectId("6154f37b7b36c03e7fbbab06"),
        "username" : "gongu",
        "favorites" : {
                "movies" : [
                        "mv1",
                        "mv2"
                ],
                "hobby" : [
                        "h1",
                        "h2",
                        "h3"
                ]
        }
}
{ "_id" : ObjectId("6154f4c67b36c03e7fbbab07"), "username" : "una" }
> db.users.update({username:"gongu"},{$push:{"favorites.movies":"mv2"}})
WriteResult({ "nMatched" : 1, "nUpserted" : 0, "nModified" : 1 })
> db.users.find().pretty()
{ "_id" : ObjectId("6154f18d7b36c03e7fbbab05"), "country" : "japan" }
{
        "_id" : ObjectId("6154f37b7b36c03e7fbbab06"),
        "username" : "gongu",
        "favorites" : {
                "movies" : [
                        "mv1",
                        "mv2",
                        "mv2"
                ],
                "hobby" : [
                        "h1",
                        "h2",
                        "h3"
                ]
        }
}
{ "_id" : ObjectId("6154f4c67b36c03e7fbbab07"), "username" : "una" }

$set을 이용하면 MONGODB가 추가되지 않고, 기존 데이터를 변경해 버렸다.
배열형식의 데이터추가를 할 때는 $addToSet, $push를 사용한다.
$push와 $addToSet의 차이점은 $addToSet은 데이터를 추가할때 중복된값은 업데이트 하지 않는다.

데이터 삭제

> db.users.remove({username:"una"})
WriteResult({ "nRemoved" : 1 })
> db.users.find()
{ "_id" : ObjectId("6154f18d7b36c03e7fbbab05"), "country" : "japan" }
{ "_id" : ObjectId("6154f37b7b36c03e7fbbab06"), "username" : "gongu", "favorites" : { "movies" : [ "mv1", "mv2", "mv2" ], "hobby" : [ "h1", "h2", "h3" ] } }
> db.users.drop()
true
> db.users.find()
>

$remove() : 데이터삭제
$drop() : 컬렉션 삭제 (컬렉션에 포함되어있던 인덱스도 모두 삭제된다)

인덱스 생성과 질의

Index는 MongoDB의 데이터쿼리를 더욱 효율적으로 할 수 있게 해준다.
Index가 없이는 collection scan (컬렉션 데이터를 하나하나) 으로 조회하므로 비효율적인다.
한 쿼리당 하나의 index만 유효하며, 두개의 index가 필요하다면 복합 index를 사용한다.

사용시 주의할 점

: 모든 인덱스를 갱신해야 하기 떄문에 모든 쓰기 작업은 인덱스 때문에 더 오래 걸림
: Collection 당 최대 64개까지 인덱스를 지닐수있지만, 2~3개만 지니는게 좋다.
: 몽고디비의 인덱스는 RDBMS와 유사하게 작동함
: 인덱스 구축시 background 옵션을 사용하면, 비동기로 작업이 가능하긴하지만 느리다.

> for(i=0;i<20000;i++){
... db.numbers.save({num:i});
... }
WriteResult({ "nInserted" : 1 })
> db.numbers.count()
20000
> db.numbers.find({num:{"$gt":19995}})
{ "_id" : ObjectId("615504a22c5c13ab570becad"), "num" : 19996 }
{ "_id" : ObjectId("615504a22c5c13ab570becae"), "num" : 19997 }
{ "_id" : ObjectId("615504a22c5c13ab570becaf"), "num" : 19998 }
{ "_id" : ObjectId("615504a22c5c13ab570becb0"), "num" : 19999 }
> db.numbers.find({num:{"$gt":19995,"$lt":19997}})
{ "_id" : ObjectId("615504a22c5c13ab570becad"), "num" : 19996 }

it : more과 같은 역할
$gt : greater than / $gte : greater than or equal to
$lt : less than / $lte : less than or equal to
$ne : not equal to

> db.numbers.createIndex({num:1})
{
        "numIndexesBefore" : 1,
        "numIndexesAfter" : 2,
        "createdCollectionAutomatically" : false,
        "ok" : 1
}
> db.numbers.getIndexes()
[
        {
                "v" : 2,
                "key" : {
                        "_id" : 1
                },
                "name" : "_id_"
        },
        {
                "v" : 2,
                "key" : {
                        "num" : 1
                },
                "name" : "num_1"
        }
]

createIndex() : 인덱스생성
getIndexes() : 인덱스 확인
_id : 자동으로 pk생성
인덱스명을 지정하지 않으면 자동으로 생성

> 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" : 4,
                "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" : "�̸���-PC",
                "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
}

num에 대한 인덱스 num_1을 사용하므로 쿼리에 해당하는 4개의 도큐먼트만을 스캔하고 쿼리 실행시간도 줄어든다.

기본적인 관리

> show dbs
admin     0.000GB
config    0.000GB
local     0.000GB
tutorial  0.001GB
> show collections
numbers
> db.stats()
{
        "db" : "tutorial",
        "collections" : 1,
        "views" : 0,
        "objects" : 20000,
        "avgObjSize" : 35,
        "dataSize" : 700000,
        "storageSize" : 262144,
        "freeStorageSize" : 0,
        "indexes" : 2,
        "indexSize" : 462848,
        "indexFreeStorageSize" : 0,
        "totalSize" : 724992,
        "totalFreeStorageSize" : 0,
        "scaleFactor" : 1,
        "fsUsedSize" : 105793134592,
        "fsTotalSize" : 495558197248,
        "ok" : 1
}
> db.numbers.stats()
{
        "ns" : "tutorial.numbers",
        "size" : 700000,
        "count" : 20000,
        "avgObjSize" : 35,
        "storageSize" : 262144,
        "freeStorageSize" : 0,
        "capped" : false,
        "wiredTiger" : {
                "metadata" : {
                        "formatVersion" : 1
                },
                "creationString" : "access_pattern_hint=none,allocation_size=4KB,app_metadata=(formatVersion=1),assert=(commit_timestamp=none,durable_timestamp=none,read_timestamp=none,write_timestamp=off),block_allocation=best,block_compressor=snappy,cache_resident=false,checksum=on,colgroups=,collator=,columns=,dictionary=0,encryption=(keyid=,name=),exclusive=false,extractor=,format=btree,huffman_key=,huffman_value=,ignore_in_memory_cache_size=false,immutable=false,import=(enabled=false,file_metadata=,repair=false),internal_item_max=0,internal_key_max=0,internal_key_truncate=true,internal_page_max=4KB,key_format=q,key_gap=10,leaf_item_max=0,leaf_key_max=0,leaf_page_max=32KB,leaf_value_max=64MB,log=(enabled=true),lsm=(auto_throttle=true,bloom=true,bloom_bit_count=16,bloom_config=,bloom_hash_count=8,bloom_oldest=false,chunk_count_limit=0,chunk_max=5GB,chunk_size=10MB,merge_custom=(prefix=,start_generation=0,suffix=),merge_max=15,merge_min=0),memory_page_image_max=0,memory_page_max=10m,os_cache_dirty_max=0,os_cache_max=0,prefix_compression=false,prefix_compression_min=4,readonly=false,source=,split_deepen_min_child=0,split_deepen_per_child=0,split_pct=90,tiered_object=false,tiered_storage=(auth_token=,bucket=,bucket_prefix=,local_retention=300,name=,object_target_size=10M),type=file,value_format=u,verbose=[],write_timestamp_usage=none",
                "type" : "file",
                "uri" : "statistics:table:collection-9-1214493195749372225",
                "LSM" : {
                        "bloom filter false positives" : 0,
                        "bloom filter hits" : 0,
                        "bloom filter misses" : 0,
                        "bloom filter pages evicted from cache" : 0,
                        "bloom filter pages read into cache" : 0,
                        "bloom filters in the LSM tree" : 0,
                        "chunks in the LSM tree" : 0,
                        "highest merge generation in the LSM tree" : 0,
                        "queries that could have benefited from a Bloom filter that did not exist" : 0,
                        "sleep for LSM checkpoint throttle" : 0,
                        "sleep for LSM merge throttle" : 0,
                        "total size of bloom filters" : 0
                },
                "block-manager" : {
                        "allocations requiring file extension" : 10,
                        "blocks allocated" : 10,
                        "blocks freed" : 0,
                        "checkpoint size" : 245760,
                        "file allocation unit size" : 4096,
                        "file bytes available for reuse" : 0,
                        "file magic number" : 120897,
                        "file major version number" : 1,
                        "file size in bytes" : 262144,
                        "minor version number" : 0
                },
                "btree" : {
                        "btree checkpoint generation" : 145,
                        "btree clean tree checkpoint expiration time" : NumberLong("9223372036854775807"),
                        "column-store fixed-size leaf pages" : 0,
                        "column-store internal pages" : 0,
                        "column-store variable-size RLE encoded values" : 0,
                        "column-store variable-size deleted values" : 0,
                        "column-store variable-size leaf pages" : 0,
                        "fixed-record size" : 0,
                        "maximum internal page key size" : 368,
                        "maximum internal page size" : 4096,
                        "maximum leaf page key size" : 2867,
                        "maximum leaf page size" : 32768,
                        "maximum leaf page value size" : 67108864,
                        "maximum tree depth" : 3,
                        "number of key/value pairs" : 0,
                        "overflow pages" : 0,
                        "pages rewritten by compaction" : 0,
                        "row-store empty values" : 0,
                        "row-store internal pages" : 0,
                        "row-store leaf pages" : 0
                },
                "cache" : {
                        "bytes currently in the cache" : 2706915,
                        "bytes dirty in the cache cumulative" : 865,
                        "bytes read into cache" : 0,
                        "bytes written from cache" : 791840,
                        "checkpoint blocked page eviction" : 0,
                        "checkpoint of history store file blocked non-history store page eviction" : 0,
                        "data source pages selected for eviction unable to be evicted" : 0,
                        "eviction gave up due to detecting an out of order on disk value behind the last update on the chain" : 0,
                        "eviction gave up due to detecting an out of order tombstone ahead of the selected on disk update" : 0,
                        "eviction gave up due to detecting an out of order tombstone ahead of the selected on disk update after validating the update chain" : 0,
                        "eviction gave up due to detecting out of order timestamps on the update chain after the selected on disk update" : 0,
                        "eviction walk passes of a file" : 0,
                        "eviction walk target pages histogram - 0-9" : 0,
                        "eviction walk target pages histogram - 10-31" : 0,
                        "eviction walk target pages histogram - 128 and higher" : 0,
                        "eviction walk target pages histogram - 32-63" : 0,
                        "eviction walk target pages histogram - 64-128" : 0,
                        "eviction walk target pages reduced due to history store cache pressure" : 0,
                        "eviction walks abandoned" : 0,
                        "eviction walks gave up because they restarted their walk twice" : 0,
                        "eviction walks gave up because they saw too many pages and found no candidates" : 0,
                        "eviction walks gave up because they saw too many pages and found too few candidates" : 0,
                        "eviction walks reached end of tree" : 0,
                        "eviction walks restarted" : 0,
                        "eviction walks started from root of tree" : 0,
                        "eviction walks started from saved location in tree" : 0,
                        "hazard pointer blocked page eviction" : 0,
                        "history store table insert calls" : 0,
                        "history store table insert calls that returned restart" : 0,
                        "history store table out-of-order resolved updates that lose their durable timestamp" : 0,
                        "history store table out-of-order updates that were fixed up by reinserting with the fixed timestamp" : 0,
                        "history store table reads" : 0,
                        "history store table reads missed" : 0,
                        "history store table reads requiring squashed modifies" : 0,
                        "history store table truncation by rollback to stable to remove an unstable update" : 0,
                        "history store table truncation by rollback to stable to remove an update" : 0,
                        "history store table truncation to remove an update" : 0,
                        "history store table truncation to remove range of updates due to key being removed from the data page during reconciliation" : 0,
                        "history store table truncation to remove range of updates due to out-of-order timestamp update on data page" : 0,
                        "history store table writes requiring squashed modifies" : 0,
                        "in-memory page passed criteria to be split" : 0,
                        "in-memory page splits" : 0,
                        "internal pages evicted" : 0,
                        "internal pages split during eviction" : 0,
                        "leaf pages split during eviction" : 0,
                        "modified pages evicted" : 0,
                        "overflow pages read into cache" : 0,
                        "page split during eviction deepened the tree" : 0,
                        "page written requiring history store records" : 0,
                        "pages read into cache" : 0,
                        "pages read into cache after truncate" : 1,
                        "pages read into cache after truncate in prepare state" : 0,
                        "pages requested from the cache" : 20066,
                        "pages seen by eviction walk" : 0,
                        "pages written from cache" : 8,
                        "pages written requiring in-memory restoration" : 0,
                        "tracked dirty bytes in the cache" : 0,
                        "unmodified pages evicted" : 0
                },
                "cache_walk" : {
                        "Average difference between current eviction generation when the page was last considered" : 0,
                        "Average on-disk page image size seen" : 0,
                        "Average time in cache for pages that have been visited by the eviction server" : 0,
                        "Average time in cache for pages that have not been visited by the eviction server" : 0,
                        "Clean pages currently in cache" : 0,
                        "Current eviction generation" : 0,
                        "Dirty pages currently in cache" : 0,
                        "Entries in the root page" : 0,
                        "Internal pages currently in cache" : 0,
                        "Leaf pages currently in cache" : 0,
                        "Maximum difference between current eviction generation when the page was last considered" : 0,
                        "Maximum page size seen" : 0,
                        "Minimum on-disk page image size seen" : 0,
                        "Number of pages never visited by eviction server" : 0,
                        "On-disk page image sizes smaller than a single allocation unit" : 0,
                        "Pages created in memory and never written" : 0,
                        "Pages currently queued for eviction" : 0,
                        "Pages that could not be queued for eviction" : 0,
                        "Refs skipped during cache traversal" : 0,
                        "Size of the root page" : 0,
                        "Total number of pages currently in cache" : 0
                },
                "checkpoint-cleanup" : {
                        "pages added for eviction" : 0,
                        "pages removed" : 0,
                        "pages skipped during tree walk" : 0,
                        "pages visited" : 1
                },
                "compression" : {
                        "compressed page maximum internal page size prior to compression" : 4096,
                        "compressed page maximum leaf page size prior to compression " : 111416,
                        "compressed pages read" : 0,
                        "compressed pages written" : 7,
                        "page written failed to compress" : 0,
                        "page written was too small to compress" : 1
                },
                "cursor" : {
                        "Total number of entries skipped by cursor next calls" : 0,
                        "Total number of entries skipped by cursor prev calls" : 0,
                        "Total number of entries skipped to position the history store cursor" : 0,
                        "Total number of pages skipped without reading by cursor next calls" : 0,
                        "Total number of pages skipped without reading by cursor prev calls" : 0,
                        "Total number of times a search near has exited due to prefix config" : 0,
                        "bulk loaded cursor insert calls" : 0,
                        "cache cursors reuse count" : 20004,
                        "close calls that result in cache" : 20006,
                        "create calls" : 4,
                        "cursor next calls that skip due to a globally visible history store tombstone" : 0,
                        "cursor next calls that skip greater than or equal to 100 entries" : 0,
                        "cursor next calls that skip less than 100 entries" : 60005,
                        "cursor prev calls that skip due to a globally visible history store tombstone" : 0,
                        "cursor prev calls that skip greater than or equal to 100 entries" : 0,
                        "cursor prev calls that skip less than 100 entries" : 1,
                        "insert calls" : 20000,
                        "insert key and value bytes" : 751426,
                        "modify" : 0,
                        "modify key and value bytes affected" : 0,
                        "modify value bytes modified" : 0,
                        "next calls" : 60005,
                        "open cursor count" : 0,
                        "operation restarted" : 0,
                        "prev calls" : 1,
                        "remove calls" : 0,
                        "remove key bytes removed" : 0,
                        "reserve calls" : 0,
                        "reset calls" : 40073,
                        "search calls" : 4,
                        "search history store calls" : 0,
                        "search near calls" : 60,
                        "truncate calls" : 0,
                        "update calls" : 0,
                        "update key and value bytes" : 0,
                        "update value size change" : 0
                },
                "reconciliation" : {
                        "approximate byte size of timestamps in pages written" : 0,
                        "approximate byte size of transaction IDs in pages written" : 0,
                        "dictionary matches" : 0,
                        "fast-path pages deleted" : 0,
                        "internal page key bytes discarded using suffix compression" : 13,
                        "internal page multi-block writes" : 0,
                        "internal-page overflow keys" : 0,
                        "leaf page key bytes discarded using prefix compression" : 0,
                        "leaf page multi-block writes" : 1,
                        "leaf-page overflow keys" : 0,
                        "maximum blocks required for a page" : 1,
                        "overflow values written" : 0,
                        "page checksum matches" : 0,
                        "page reconciliation calls" : 2,
                        "page reconciliation calls for eviction" : 0,
                        "pages deleted" : 0,
                        "pages written including an aggregated newest start durable timestamp " : 0,
                        "pages written including an aggregated newest stop durable timestamp " : 0,
                        "pages written including an aggregated newest stop timestamp " : 0,
                        "pages written including an aggregated newest stop transaction ID" : 0,
                        "pages written including an aggregated newest transaction ID " : 0,
                        "pages written including an aggregated oldest start timestamp " : 0,
                        "pages written including an aggregated prepare" : 0,
                        "pages written including at least one prepare" : 0,
                        "pages written including at least one start durable timestamp" : 0,
                        "pages written including at least one start timestamp" : 0,
                        "pages written including at least one start transaction ID" : 0,
                        "pages written including at least one stop durable timestamp" : 0,
                        "pages written including at least one stop timestamp" : 0,
                        "pages written including at least one stop transaction ID" : 0,
                        "records written including a prepare" : 0,
                        "records written including a start durable timestamp" : 0,
                        "records written including a start timestamp" : 0,
                        "records written including a start transaction ID" : 0,
                        "records written including a stop durable timestamp" : 0,
                        "records written including a stop timestamp" : 0,
                        "records written including a stop transaction ID" : 0
                },
                "session" : {
                        "object compaction" : 0,
                        "tiered operations dequeued and processed" : 0,
                        "tiered operations scheduled" : 0,
                        "tiered storage local retention time (secs)" : 0,
                        "tiered storage object size" : 0
                },
                "transaction" : {
                        "race to read prepared update retry" : 0,
                        "rollback to stable history store records with stop timestamps older than newer records" : 0,
                        "rollback to stable inconsistent checkpoint" : 0,
                        "rollback to stable keys removed" : 0,
                        "rollback to stable keys restored" : 0,
                        "rollback to stable restored tombstones from history store" : 0,
                        "rollback to stable restored updates from history store" : 0,
                        "rollback to stable skipping delete rle" : 0,
                        "rollback to stable skipping stable rle" : 0,
                        "rollback to stable sweeping history store keys" : 0,
                        "rollback to stable updates removed from history store" : 0,
                        "transaction checkpoints due to obsolete pages" : 0,
                        "update conflicts" : 0
                }
        },
        "nindexes" : 2,
        "indexBuilds" : [ ],
        "totalIndexSize" : 462848,
        "totalSize" : 724992,
        "indexSizes" : {
                "_id_" : 225280,
                "num_1" : 237568
        },
        "scaleFactor" : 1,
        "ok" : 1
}

show dbs : 시스템상의 모든 데이터베이스를 보여준다.
show collections : 현재 사용 중인 데이터베이스에서 정의된 모든 컬렉션을 보여준다.
stats() : 좀 더 하위 계층의 정보를 얻을 수 있다.

> db.runCommand
function(obj, extra, queryOptions) {
    "use strict";

    // Support users who call this function with a string commandName, e.g.
    // db.runCommand("commandName", {arg1: "value", arg2: "value"}).
    var mergedObj = this._mergeCommandOptions(obj, extra);

    // if options were passed (i.e. because they were overridden on a collection), use them.
    // Otherwise use getQueryOptions.
    var options = (typeof (queryOptions) !== "undefined") ? queryOptions : this.getQueryOptions();

    try {
        return this._runCommandImpl(this._name, mergedObj, options);
    } catch (ex) {
        // When runCommand flowed through query, a connection error resulted in the message
        // "error doing query: failed". Even though this message is arguably incorrect
        // for a command failing due to a connection failure, we preserve it for backwards
        // compatibility. See SERVER-18334 for details.
        if (ex.message.indexOf("network error") >= 0) {
            throw new Error("error doing query: failed: " + ex.message);
        }
        throw ex;
    }
}

명령어가 작동하는 방식.

도움말 얻기

db.help() : 데이터베이스에 대해 일반적으로 수앻되는 메서드의 리스트를 보여준다.
db.numbers.help() : 컬렉션에 대해 수행되는 메서드를 보여준다.

> db.numbers.save({num:111111111111})
WriteResult({ "nInserted" : 1 })
> db.numbers.save
function(obj, opts) {
    if (obj == null)
        throw Error("can't save a null");

    if (typeof (obj) == "number" || typeof (obj) == "string")
        throw Error("can't save a number or string");

    if (typeof (obj._id) == "undefined") {
        obj._id = new ObjectId();
        return this.insert(obj, opts);
    } else {
        return this.update({_id: obj._id}, obj, Object.merge({upsert: true}, opts));
    }
}
> db.numbers.insert
function(obj, options) {
    if (!obj)
        throw Error("no object passed to insert!");

    options = typeof (options) === 'undefined' ? {} : options;

    var flags = 0;

    var wc = undefined;
    var allowDottedFields = false;
    if (options === undefined) {
        // do nothing
    } else if (typeof (options) == 'object') {
        if (options.ordered === undefined) {
            // do nothing, like above
        } else {
            flags = options.ordered ? 0 : 1;
        }

        if (options.writeConcern)
            wc = options.writeConcern;
        if (options.allowdotted)
            allowDottedFields = true;
    } else {
        flags = options;
    }

    // 1 = continueOnError, which is synonymous with unordered in the write commands/bulk-api
    var ordered = ((flags & 1) == 0);

    if (!wc)
        wc = this._createWriteConcern(options);

    var result = undefined;
    var startTime =
        (typeof (_verboseShell) === 'undefined' || !_verboseShell) ? 0 : new Date().getTime();

    if (this.getMongo().writeMode() != "legacy") {
        // Bit 1 of option flag is continueOnError. Bit 0 (stop on error) is the default.
        var bulk = ordered ? this.initializeOrderedBulkOp() : this.initializeUnorderedBulkOp();
        var isMultiInsert = Array.isArray(obj);

        if (isMultiInsert) {
            obj.forEach(function(doc) {
                bulk.insert(doc);
            });
        } else {
            bulk.insert(obj);
        }

        try {
            result = bulk.execute(wc);
            if (!isMultiInsert)
                result = result.toSingleResult();
        } catch (ex) {
            if (ex instanceof BulkWriteError) {
                result = isMultiInsert ? ex.toResult() : ex.toSingleResult();
            } else if (ex instanceof WriteCommandError) {
                result = ex;
            } else {
                // Other exceptions rethrown as-is.
                throw ex;
            }
        }
    } else {
        if (typeof (obj._id) == "undefined" && !Array.isArray(obj)) {
            var tmp = obj;  // don't want to modify input
            obj = {_id: new ObjectId()};
            for (var key in tmp) {
                obj[key] = tmp[key];
            }
        }

        this.getMongo().insert(this._fullName, obj, flags);

        // enforce write concern, if required
        if (wc)
            result = this.runCommand("getLastError", wc instanceof WriteConcern ? wc.toJSON() : wc);
    }

    this._lastID = obj._id;
    this._printExtraInfo("Inserted", startTime);
    return result;
}

save 와 insert의 방식을 알고싶을 경우 어떻게 구현되어있는지 확인해보자.

Leave a Comment