MongoDB 常用命令
1、链接或登陆命令
mongo -h 192.168.10.1 --port 27019 -u admin -p --authenticationDatabase admin
或
use admin
db.auth('admin','password')
2、查看数据库信息
show dbs
或者
db.runCommand({"listDatabases: 1 "})
3、查看表信息
show tables
show collections
4、关闭mongod服务
db.shutdownServer()
5、查看版本信息
db.version()
6、查看复制集的配置
rs.config()
7、或者复制集的状态
rs.status()
8、查看节点是否是master节点
db.isMaster()
9、查看当前配置
db.serverCmdLineOpts()
10、在主库查看复制集的信息
db.printReplcationInfo()
11、查看复制集slave的配置
db.printSlaveReplicationInfo()
12、让主节点降级为备节点,并且在60秒内无法成为主节点,等待5秒,超时回滚。
db.stepDown(60,5)
13、阻止备份节点在10000秒成为主节点,用于维护主节点。
rs.freeze(1000)
14、重命名表名
db.mydb.renameCollection('mydb_1')
15、查看库中当前正在执行的所有操作
db.currentOp()
16、切割日志文件(日志切割)
useadmin
db.runCommand({logRotate: 1})
17、锁库只允许都操作
db.fsyncLock()
18、解锁,可能无法正常解锁,需要运行db.currentOp() 查看解锁是否成功。
db.fsyncUnlock()
19、查看当前数据库的profile状态
db.getProfilingStatus()
20、查看集合的信息
db.my_coll.status()
21、查看当前对某个库执行的操作
db.mydb.currentOp({"ns":"mydb"})
22、杀死某个慢查询或错误操作
db.killOp()
23、查看慢查询(大于1秒)
db.currentOp().inprog.forEach(function(item) {if (item.ns != "local.oplog.rs" && item.ns != "local.replset.minvalid" && item.secs_running > 1) print (JSON.stringify(item))})
分片管理
1、获取sharding 集群balance是否开启
sh.getBalancerState()
2、关闭balancer
sh.stopBalancer()
3、开启balancer
sh.startBalancer()
4、针对students库的grades集合关闭balancer
sh.disableBalancing("students.grades")
5、针对students库的grades集合开启balancer
sh.enableBalancing("students.grades")
6、指定balancer启动的时间段
use config
db.setting.update(
{ _id: "balancer" },
{ $set: { activeWindow : { start: "02", stop: "07"}}},
{upsert: true}
)
7、
管理mongod服务
1、查看当前是否有流量
db.serverStatus().opcounters
2、查看流量
mongoreplay monitor -i eth0 -e 'port 27019' --collect json | grep -vE '{"request_data":null | replSet|"ns":"local"'
或者
./mongoreplay monitor -i eth0 -e 'port 27020' --collect json|grep -vE '("request_data":null|replSet|"ns":"local"|"command":"insert"|"command":"update")'
3、 查看复制是否还有流量
db.serverStatus().opcountersRepl
4、该值一直很高,那么存在大量请求等待锁定的机会,这表示可能会影响性能的并发问题。
db.serverStatus().globalLock.currentQueue.total
5、
该值快速增长则表示物理内存太少,整个集合访问也会发生低效率的情况
db.serverStatus().extra_info.page_faults
6、正在进行或正在排队的链接总是统计
db.serverStatus().globalLock.activeClients
7、链接到当前数据库的客户端数量
db.serverStatus().connections.current
8、未使用的连接数
db.serverStatus.connection.available
9、内存的相关信息
db.serverStatus().tcmalloc.tcmalloc.formattedString
10、更详细的serverStatus:
db.serverStatus({"repl":1})
db.runCommand({"serverStatus":1,"repl":1})
db.getLogComponents()
db.setLogLevel(-1,"command")
11、在线变更cache_size:
db.adminCommand({setParameter: 1,writeTigerEngineRuntimeConfig:"cache_size=30G"})
db.serverStatus().wiredTiger.cache中的maxnum bytes configured
12、查找有关test1集合的相关锁信息
db.locks.find({"state": 2})
13、查找那些是jumbo chunk
db.chunks.find({shard: "rs1","jumbo": true })
14、能看到具体的jumbo chunk
sh.status(true)
插入
for(i=1;i<500;i+=2) db.my_coll.insert({x:i})
或者
for(i=1;i<500;i++) db.my_coll.insert({x:i})