MongoDB 数据库管理(不定时更新)

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   :参数

 View Code

各种备份方式:

复制代码
无账号、密码
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 :参数

 View Code

各种还原方式:

复制代码
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" }
复制代码
原文地址:https://www.cnblogs.com/ExMan/p/9551597.html