之前的幾篇文章大致說了副本集的搭建、副本集的管理,現在說下MongoDB數據庫的管理。數據庫管理包括:備份、還原、導入、導出、服務器管理等。
一:查看服務器狀態,查看命令行參數。db.serverStatus()、db.serverCmdLineOpts()
zjy:PRIMARY> db.serverStatus() { "host" : "zhoujinyi", "version" : "3.0.4", "process" : "mongod", "pid" : NumberLong(3939), "uptime" : 149427, "uptimeMillis" : NumberLong(149427393), "uptimeEstimate" : 140539, "localTime" : ISODate("2015-07-01T14:06:12.922Z"), "asserts" : { "regular" : 0, "warning" : 0, "msg" : 0, "user" : 30, "rollovers" : 0 }, "backgroundFlushing" : { "flushes" : 2490, "total_ms" : 10410, "average_ms" : 4.180722891566265, "last_ms" : 10, "last_finished" : ISODate("2015-07-01T14:05:47.284Z") }, "connections" : { "current" : 7, "available" : 43, "totalCreated" : NumberLong(10016) }, ... ... "network" : { "bytesIn" : 23165291, "bytesOut" : 25295567, "numRequests" : 209093 }, "opcounters" : { "insert" : 9, "query" : 53, "update" : 9, "delete" : 0, "getmore" : 59219, "command" : 149822 }, "opcountersRepl" : { "insert" : 0, "query" : 0, "update" : 0, "delete" : 0, "getmore" : 0, "command" : 0 }, "repl" : { "setName" : "zjy", "setVersion" : 31303, "ismaster" : true, "secondary" : false, "hosts" : [ "127.0.0.1:27017", "127.0.0.1:27018", "127.0.0.1:27019" ], "primary" : "127.0.0.1:27017", "me" : "127.0.0.1:27017", "electionId" : ObjectId("5592be327c7062c30c3bff24"), "rbid" : 652411007 }, "storageEngine" : { "name" : "mmapv1" }, "writeBacksQueued" : false, "mem" : { "bits" : 64, "resident" : 130, "virtual" : 9710, "supported" : true, "mapped" : 4574, "mappedWithJournal" : 9148 }, ... ... "ok" : 1 }
通過上面看到MongoDB的版本、后台刷寫情況、副本集情況、操作數量情況、進出網絡情況、連接數情況和內存情況。
其中內存相關字段的含義是:單位是M
mapped:映射到內存的數據大小
visze:占用的虛擬內存大小
res:實際使用的內存大小
在上面的結果中,virtual是mapped的兩倍,而mapped等於數據文件的大小,所以說vsize是數據文件的兩倍,之所以會這樣,是因為本例中,MongoDB開啟了journal,需要在內存里多映射一次數據文件,如果關閉journal,則virtual和mapped大致相當。
也可以通過mongostat來查看:
root@zhoujinyi:~# mongostat insert query update delete getmore command flushes mapped vsize res faults qr|qw ar|aw netIn netOut conn set repl time *0 *0 *0 *0 1 2|0 0 4.5G 9.5G 133.0M 0 0|0 0|0 262b 11k 7 zjy PRI 10:23:13 *0 *0 *0 *0 0 2|0 0 4.5G 9.5G 133.0M 0 0|0 0|0 215b 11k 7 zjy PRI 10:23:14 *0 *0 *0 *0 0 2|0 0 4.5G 9.5G 133.0M 0 0|0 0|0 215b 11k 7 zjy PRI 10:23:15
faults:查詢從磁盤讀取數據,標志服務器未達到最佳,所需的數據並未完全保存找內存中
qr/qw:隊列等待的數目。
ar/aw:活動客戶端的數目。
conn:打開的連接數。
flushes:數據刷寫到磁盤的數目。
vsize:使用虛擬內存大小。
mapped:隱射的內存大小,約等於數據目錄大小。
查看命令行參數:
zjy:PRIMARY> db.serverCmdLineOpts() { "argv" : [ "mongod", "-f", "/etc/mongodb/mongodb_27017.conf" ], "parsed" : { "config" : "/etc/mongodb/mongodb_27017.conf", "diaglog" : 3, "net" : { "maxIncomingConnections" : 50, "port" : 27017, "unixDomainSocket" : { "pathPrefix" : "/tmp" } }, "processManagement" : { "fork" : true, "pidFilePath" : "/var/run/mongo_27017.pid" }, "replication" : { "replSet" : "zjy/127.0.0.1:27018" }, "storage" : { "dbPath" : "/usr/local/mongo1/", "mmapv1" : { "nsSize" : 16 } }, "systemLog" : { "destination" : "file", "logAppend" : true, "path" : "/var/log/mongodb/mongodb1.log" } }, "ok" : 1 }
二:查看數據庫/表狀態,db.stats()/db.coll.stats() | M為單位:db.stats(1024*1024)/db.coll.stats(1024*1024)
zjy:PRIMARY> db.stats() { "db" : "test", "collections" : 7, "objects" : 36, "avgObjSize" : 417.1111111111111, "dataSize" : 15016, #數據文件大小。 "storageSize" : 1093632, #存儲空間大小:datasize+集合兩端預留的未使用空間。 "numExtents" : 7, "indexes" : 4, "indexSize" : 32704, "fileSize" : 67108864, #物理文件大小:包括預分配 "nsSizeMB" : 16, "extentFreeList" : { "num" : 0, "totalSize" : 0 }, "dataFileVersion" : { "major" : 4, "minor" : 22 }, "ok" : 1 }
通過上面看到數據庫的名稱,集合(表)數量,索引數量、大小,數據文件大小,存儲空間大小和物理文件大小。
三:查看當前Query執行情況:db.currentOP():
zjy:PRIMARY> db.currentOP() { "inprog" : [ { "desc" : "conn4732", #可與日志信息聯系起來 "threadId" : "0x33903c0", "connectionId" : 4732, #連接ID "opid" : 221672, #操作標識,可以用這個ID來終止該操作:db.killOP(opid) "active" : true, #表示線程是否在運行 "secs_running" : 4, #執行的時間 "microsecs_running" : NumberLong(4999899), "op" : "getmore", #操作類型:插入、刪除、更新、查詢 "ns" : "local.oplog.rs", #操作的集合 "query" : { "ts" : { "$gte" : Timestamp(1435674461, 1) } }, "client" : "127.0.0.1:52101", "numYields" : 0, #表示該操作交出鎖,而使其他操作得以運行。 "locks" : { #鎖信息 }, "waitingForLock" : false, "lockStats" : { "Global" : { "acquireCount" : { "r" : NumberLong(10) } }, "MMAPV1Journal" : { "acquireCount" : { "r" : NumberLong(5) } }, "Database" : { "acquireCount" : { "r" : NumberLong(5) } }, "oplog" : { "acquireCount" : { "R" : NumberLong(5) } } } }
...
...
通過上面看到當前執行的進程,類似MySQL的show processlist。可以添加過濾條件:
zjy:PRIMARY> db.currentOP({"ns":"test"})
四:監控MongoDB各個狀態:mongotop、mongostat
root@zhoujinyi:~# mongotop #查看那個幾個最繁忙 ns total read write 2015-07-01T11:24:43-04:00 abc 0ms 0ms 0ms abc.AOE 0ms 0ms 0ms abc.aoe 0ms 0ms 0ms abc.system.indexes 0ms 0ms 0ms abc.system.js 0ms 0ms 0ms abc.system.namespaces 0ms 0ms 0ms abc.test 0ms 0ms 0ms admin.system.indexes 0ms 0ms 0ms admin.system.namespaces 0ms 0ms 0ms admin.system.roles
root@zhoujinyi:~# mongostat insert query update delete getmore command flushes mapped vsize res faults qr|qw ar|aw netIn netOut conn set repl time *0 *0 *0 *0 0 2|0 0 4.5G 9.5G 133.0M 0 0|0 0|0 215b 11k 7 zjy PRI 11:26:21 *0 *0 *0 *0 0 2|0 0 4.5G 9.5G 133.0M 0 0|0 0|0 215b 11k 7 zjy PRI 11:26:22 *0 *0 *0 *0 0 2|0 0 4.5G 9.5G 133.0M 0 0|0 0|0 215b 11k 7 zjy PRI 11:26:23 *0 *0 *0 *0 1 2|0 0 4.5G 9.5G 133.0M 0 0|0 0|0 262b 11k 7 zjy PRI 11:26:24
上面insert、query、update、delete、getmore、command 每種對應操作的發生次數。其中faults表示訪問失敗數,數據從內存交換出去,放到swap。值越小越好,最好不要大於100。
flushes:表示刷寫到磁盤的次數。 mapped:表示映射到內存的數量,約等於數據目錄大小。 vsize:表示正在使用的虛擬內存大小,通常為數據目錄的2倍。(一次用於映射,一次用於日志系統) res:表示正在使用的內存大小。 qr|qw:表示讀寫操作隊列大小,即有多少讀寫操作被阻塞,等待進行處理。 ar|aw:表示活動客戶端的數量,即正在進行讀寫操作的客戶端。 netId:表示通過網絡傳輸進來的字節數。 netou:t表示通過網絡傳輸出的字節數。 Conn:表示服務器打開的連接數。 time:表示統計的時間。
其中mongostat加上--discover 可以查看到副本集和分片集群的所有成員狀態
五:日志分割,db.adminCommand({"logRotate":1})
zjy:PRIMARY> db.adminCommand({"logRotate":1}) { "ok" : 1 }
類似MySQL的flush log。
六:數據庫備份、還原,mongodump、mongorestore、mongoimport、mongoexport
mongodump --help :參數

Export MongoDB data to BSON files. Options: --help produce help message -v [ --verbose ] be more verbose (include multiple times for more verbosity e.g. -vvvvv) --quiet silence all non error diagnostic messages --version print the program's version and exit -h [ --host ] arg mongo host to connect to ( <set name>/s1,s2 for sets) --port arg server port. Can also use --host hostname:port --ipv6 enable IPv6 support (disabled by default) -u [ --username ] arg username -p [ --password ] arg password --authenticationDatabase arg user source (defaults to dbname) --authenticationMechanism arg (=MONGODB-CR) authentication mechanism --gssapiServiceName arg (=mongodb) Service name to use when authenticating using GSSAPI/Kerberos --gssapiHostName arg Remote host name to use for purpose of GSSAPI/Kerberos authentication --dbpath arg directly access mongod database files in the given path, instead of connecting to a mongod server - needs to lock the data directory, so cannot be used if a mongod is currently accessing the same path --directoryperdb each db is in a separate directory (relevant only if dbpath specified) --journal enable journaling (relevant only if dbpath specified) -d [ --db ] arg database to use -c [ --collection ] arg collection to use (some commands) -o [ --out ] arg (=dump) output directory or "-" for stdout -q [ --query ] arg json query --oplog Use oplog for point-in-time snapshotting --repair try to recover a crashed database --forceTableScan force a table scan (do not use $snapshot) --dumpDbUsersAndRoles Dump user and role definitions for the given database
各種備份方式:
無賬號、密碼 mongodump -o backup #備份所有數據庫到backup目錄下,每個數據庫一個文件,除local數據庫外。 mongodump -d abc -o backup #備份abc數據庫到backup目錄下。 mongodump -d abc -c ddd -o backup #備份abc數據庫下的ddd集合。 #有賬號、密碼 mongodump -udba -pdba -d abc -c ddd -o backup #備份abc數據庫下的ddd集合。 mongodump --host=127.0.0.1 --port=27017 -udba -p --db=abc --collection=ddd -o backup
這里需要注意的是:在認證備份中,比如在abc數據庫中,需要其有dba這個賬號才可以執行備份,要是abc數據庫里沒有賬號,那么需要在admin上認證,再執行需要加:authenticationDatabase 參數:指定保存用戶憑證的數據庫,沒有指定則去-d指定的數據庫認證。最好還是設置專本備份的賬號。
mongodump -udba -pdba -d abc --authenticationDatabase admin -o backup #在admin數據庫下認證之后再去備份abc數據庫。
mongorestore --help :參數

Import BSON files into MongoDB. usage: mongorestore [options] [directory or filename to restore from] Options: --help produce help message -v [ --verbose ] be more verbose (include multiple times for more verbosity e.g. -vvvvv) --quiet silence all non error diagnostic messages --version print the program's version and exit -h [ --host ] arg mongo host to connect to ( <set name>/s1,s2 for sets) --port arg server port. Can also use --host hostname:port --ipv6 enable IPv6 support (disabled by default) -u [ --username ] arg username -p [ --password ] arg password --authenticationDatabase arg user source (defaults to dbname) --authenticationMechanism arg (=MONGODB-CR) authentication mechanism --gssapiServiceName arg (=mongodb) Service name to use when authenticating using GSSAPI/Kerberos --gssapiHostName arg Remote host name to use for purpose of GSSAPI/Kerberos authentication --dbpath arg directly access mongod database files in the given path, instead of connecting to a mongod server - needs to lock the data directory, so cannot be used if a mongod is currently accessing the same path --directoryperdb each db is in a separate directory (relevant only if dbpath specified) --journal enable journaling (relevant only if dbpath specified) -d [ --db ] arg database to use -c [ --collection ] arg collection to use (some commands) --objcheck validate object before inserting (default) --noobjcheck don't validate object before inserting --filter arg filter to apply before inserting --drop drop each collection before import --oplogReplay replay oplog for point-in-time restore --oplogLimit arg include oplog entries before the provided Timestamp (seconds[:ordinal]) during the oplog replay; the ordinal value is optional --keepIndexVersion don't upgrade indexes to newest version --noOptionsRestore don't restore collection options --noIndexRestore don't restore indexes --restoreDbUsersAndRoles Restore user and role definitions for the given database --w arg (=0) minimum number of replicas per write
各種還原方式:
mongorestore -udba -pdba -d abc backup/abc #還原abc數據庫。 mongorestore -udba -pdba -d abc --drop backup/abc #還原之前先刪除原來數據庫(集合)。 mongorestore -udba -pdba -d abc -c ddd --drop backup/abc/ddd.bson #還原abc庫中的ddd集合。 mongorestore --host=127.0.0.1 --port=27017 -udba -pdba -d abc -c test --drop backup/abc/test.bson #還原abc庫中的test集合。 mongorestore --host=127.0.0.1 --port=27017 -udba -pdba -d abc -c ooo --drop backup/abc/test.bson #還原abc庫中的test集合到ooo集合。
mongoexport --help :參數

Export MongoDB data to CSV, TSV or JSON files. Options: --help produce help message -v [ --verbose ] be more verbose (include multiple times for more verbosity e.g. -vvvvv) --quiet silence all non error diagnostic messages --version print the program's version and exit -h [ --host ] arg mongo host to connect to ( <set name>/s1,s2 for sets) --port arg server port. Can also use --host hostname:port --ipv6 enable IPv6 support (disabled by default) -u [ --username ] arg username -p [ --password ] arg password --authenticationDatabase arg user source (defaults to dbname) --authenticationMechanism arg (=MONGODB-CR) authentication mechanism --gssapiServiceName arg (=mongodb) Service name to use when authenticating using GSSAPI/Kerberos --gssapiHostName arg Remote host name to use for purpose of GSSAPI/Kerberos authentication --dbpath arg directly access mongod database files in the given path, instead of connecting to a mongod server - needs to lock the data directory, so cannot be used if a mongod is currently accessing the same path --directoryperdb each db is in a separate directory (relevant only if dbpath specified) --journal enable journaling (relevant only if dbpath specified) -d [ --db ] arg database to use -c [ --collection ] arg collection to use (some commands) -f [ --fields ] arg comma separated list of field names e.g. -f name,age --fieldFile arg file with field names - 1 per line -q [ --query ] arg query filter, as a JSON string, e.g., '{x:{$gt:1}}' --csv export to csv instead of json -o [ --out ] arg output file; if not specified, stdout is used --jsonArray output to a json array rather than one object per line -k [ --slaveOk ] arg (=1) use secondaries for export if available, default true --forceTableScan force a table scan (do not use $snapshot) --skip arg (=0) documents to skip, default 0 --limit arg (=0) limit the numbers of documents returned, default all --sort arg sort order, as a JSON string, e.g., '{x:1}'
mongoexport -udba -pdba -dabc -cddd --authenticationDatabase admin -o backup/ddd.txt #導出txt文本 mongoexport -udba -pdba -dabc -cddd -f sno,sname --authenticationDatabase admin -o backup/ddd.txt #指定字段導出txt文本 mongoexport -udba -pdba -dabc -cddd -f sno,sname --csv --authenticationDatabase admin -o backup/ddd.csv #導出成csv格式的需要指定字段-f mongoexport -udba -pdba -dabc -cddd -q '{"sno":{"$gte":5}}' -f sno,sname --csv --authenticationDatabase admin -o backup/ddd.csv #按照-q里的條件導出
mongoimport --help :參數

Import CSV, TSV or JSON data into MongoDB. When importing JSON documents, each document must be a separate line of the input file. Example: mongoimport --host myhost --db my_cms --collection docs < mydocfile.json Options: --help produce help message -v [ --verbose ] be more verbose (include multiple times for more verbosity e.g. -vvvvv) --quiet silence all non error diagnostic messages --version print the program's version and exit -h [ --host ] arg mongo host to connect to ( <set name>/s1,s2 for sets) --port arg server port. Can also use --host hostname:port --ipv6 enable IPv6 support (disabled by default) -u [ --username ] arg username -p [ --password ] arg password --authenticationDatabase arg user source (defaults to dbname) --authenticationMechanism arg (=MONGODB-CR) authentication mechanism --gssapiServiceName arg (=mongodb) Service name to use when authenticating using GSSAPI/Kerberos --gssapiHostName arg Remote host name to use for purpose of GSSAPI/Kerberos authentication --dbpath arg directly access mongod database files in the given path, instead of connecting to a mongod server - needs to lock the data directory, so cannot be used if a mongod is currently accessing the same path --directoryperdb each db is in a separate directory (relevant only if dbpath specified) --journal enable journaling (relevant only if dbpath specified) -d [ --db ] arg database to use -c [ --collection ] arg collection to use (some commands) -f [ --fields ] arg comma separated list of field names e.g. -f name,age --fieldFile arg file with field names - 1 per line --ignoreBlanks if given, empty fields in csv and tsv will be ignored --type arg type of file to import. default: json (json,csv,tsv) --file arg file to import from; if not specified stdin is used --drop drop collection first --headerline first line in input file is a header (CSV and TSV only) --upsert insert or update objects that already exist --upsertFields arg comma-separated fields for the query part of the upsert. You should make sure this is indexed --stopOnError stop importing at first error rather than continuing --jsonArray load a json array, not one item per line. Currently limited to 16MB.
mongoimport -udba -pdba -dabc -ciii --authenticationDatabase admin < backup/ddd.txt #導入到iii集合 mongoimport -udba -pdba -dabc -ceee --type=csv --headerline --authenticationDatabase admin < backup/ddd.csv #csv導入,需要指定headerline mongoimport -udba -pdba -dabc -ceee --type=csv --headerline --ignoreBlanks --drop --authenticationDatabase admin < backup/ddd.csv #不導入空字段,指定ignoreBlanks。
七:壓縮數據文件,compact
zjy:PRIMARY> db.runCommand({compact:"cdt1"}) #整理並重組數據文件中指定集合的數據結構,不會釋放磁盤空間。 { "ok" : 1 }
八:修復索引、驗證集合,reindex,validate
zjy:PRIMARY> db.cdt1.reIndex() #修復索引 { "nIndexesWas" : 2, "nIndexes" : 2, "indexes" : [ { "key" : { "_id" : 1 }, "name" : "_id_", "ns" : "cde.cdt1" }, { "unique" : true, "key" : { "b" : 1, "date" : 1 }, "name" : "b_1_date_1", "ns" : "cde.cdt1" } ], "ok" : 1 }
zjy:PRIMARY> db.abc.validate() #驗證集合是否有問題,驗證集合內容 { "ns" : "test.abc", "datasize" : 672, "nrecords" : 6, "lastExtentSize" : 8192, "firstExtent" : "0:5000 ns:test.abc", "lastExtent" : "0:5000 ns:test.abc", "extentCount" : 1, "firstExtentDetails" : { "loc" : "0:5000", "xnext" : "null", "xprev" : "null", "nsdiag" : "test.abc", "size" : 8192, "firstRecord" : "0:50b0", "lastRecord" : "0:5330" }, "deletedCount" : 2, #刪除的文檔數量 "deletedSize" : 7248, #刪除的文檔大小 "nIndexes" : 1, "keysPerIndex" : { "test.abc.$_id_" : 6 }, "valid" : true, "errors" : [ ], "warning" : "Some checks omitted for speed. use {full:true} option to do more thorough scan.", #使用true,可以看詳細信息:db.abc.validate(true) "ok" : 1 }
九:日志Journal相關,通過db.serverstatus()查看,相關介紹:文章1和文章2
zjy:PRIMARY> db.serverStatus().dur { "commits" : 15, #在journalCommitInterval時間內提交的操作數 "journaledMB" : 0.032768, #在journalCommitInterval時間內寫到journal文件中的數據量 "writeToDataFilesMB" : 0.00509, #在journalCommitInterval時間內從journal刷新到磁盤的數據量 "compression" : 6.017998163452709,#表示客戶端提交寫入到journal的數據的壓縮比率,注意,寫入到journal的數據並不是全部的數據。( journaled_size_of_data / uncompressed_size_of_data ) "commitsInWriteLock" : 0, #在有寫鎖的情況下提交的數量,這表示寫的壓力很大 "earlyCommits" : 0, #表示在journalCommitInterval之前的時間,mongod請求提交的次數。用這個參數確定journalCommitInterval是不是設置的過長。 "timeMs" : { "dt" : 3042, "prepLogBuffer" : 0, #從privateView映射到Logbuffer的時間 "writeToJournal" : 3, #從logbuffer刷新到journalfile 的時間 "writeToDataFiles" : 0, #從journalbuffer映射到MMF,然后從MMF刷新到磁盤的時間,文件系統和磁盤會影響寫入性能 "remapPrivateView" : 0 #重新映射數據到PrivateView的時間,越小性能越好 }, "journalCommitIntervalMs" : 200 }
十:刷寫並鎖 db.fsyncLock(),db.fsyncUnlock()
drug:PRIMARY>db.fsyncLock() #刷寫到磁盤,並鎖住數據庫。此時數據庫只能讀,不能寫。保證了數據的一致性,在此可以進行復制文件或則快照備份 { "info" : "now locked against writes, use db.fsyncUnlock() to unlock", "seeAlso" : "http://dochub.mongodb.org/core/fsynccommand", "ok" : 1 } drug:PRIMARY> db.currentOP() #查看鎖情況 { "inprog" : [ ... ... ], "fsyncLock" : true, "info" : "use db.fsyncUnlock() to terminate the fsync write/snapshot lock" } drug:PRIMARY> db.fsyncUnlock() #解鎖 { "ok" : 1, "info" : "unlock completed" }
十一: