设置日志级别

db.adminCommand( { setParameter: 1, logLevel: 2 } )

慢操作配置

https://www.mongodb.com/docs/v5.0/reference/configuration-options/#mongodb-setting-operationProfiling.slowOpSampleRate

operationProfiling:
   mode: all
   filter: '{ op: "query", millis: { $gt: 2000 } }'

operationProfiling:
   mode: all
   slowOpThresholdMs: 2000
   slowOpSampleRate: 1

慢日志查询

//查询耗时2s
db.getCollection("system.profile").find({millis: {$gt: 2000}})
//设置监控级别
db.setProfilingLevel(1, { slowms: 2000 })
//查询TOP 10慢操作
db.system.profile.find().limit(10).sort( { ts : -1 } ).pretty()

写操作验证

db.products.insert(
   { item: "envelopes", qty : 100, type: "Clasp" },
   { writeConcern: { w: "majority" , wtimeout: 5000 } }
)

修改默认写

cfg = rs.conf()
cfg.settings.getLastErrorDefaults = { w: "majority", wtimeout: 5000 }
rs.reconfig(cfg)

节点切换

//降级
rs.stepDown(30)

安全

账号管理

// 管理用户
db.createUser({ user: "admin", pwd: "admin", roles: [{ role: "userAdminAnyDatabase", db: "admin" }] })
// 管理数据库
db.createUser({user: "root",pwd: "root", roles: [ { role: "root", db: "admin" } ]})
// 普通库管理员
db.createUser({user: "test",pwd: "test", roles: [ { role: "dbAdmin", db: "test" } ]})

开启认证

security:
   authorization: enabled
   keyFile: /Users/grant/Downloads/keyFile/key.key

生成key

openssl rand -base64 756 > <path-to-keyfile>
chmod 400 <path-to-keyfile>

登陆账号

db.getSiblingDB("admin").auth("root", passwordPrompt())

mongo --port 27017 -u myUserAdmin --authenticationDatabase 'admin' -p

压缩文件

use local
db.runCommand({ "compact" : "oplog.rs" } )
注意:维护时段,不能有写入操作