MongoDB 数据库管理(不定时更新)
之前的几篇文章大致说了副本集的搭建、副本集的管理,现在说下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