数据库维护和性能优化:
- 查看数据库状态:db.stats()
- 查看集合状态:
db.collection_name.stats()
- 查看索引使用情况:
db.collection_name.getIndexes()
- 重新生成集合的索引:
db.collection_name.reIndex()
- 查看查询执行计划:
db.collection_name.find({ ... }).explain()
- 查看库大小:db.stats();
- 查看集合大小:db.js_user.stats();
db.js_wx_setting_menu.storageSize();
db.js_html_alias.totalIndexSize();
故障排除和监控:
查看当前正在进行的操作:
db.currentOp() ////终止事务:db.adminCommand( { "killOp": 1, "op": "d-m5ebbc7a56ba0164:998043313" } )
使用db.currentOp()和db.currentOp(true):这两个命令可以帮助你获取当前正在运行的操作的详细信息。db.currentOp(true)会返回更多的细节,包括锁信息,这可能帮助你理解
查看运行时间超过5S的:
db.currentOp({"active": true,"secs_running": { "$gt": 5 }})
查询指定集合的操作:
db.currentOp({"query": { "$exists": true },"ns": "yourDatabase.yourCollection"})
查看特定的类型:
db.currentOp({"query": { "$exists": true },"op": "insert"})
查看数据库锁信息:
db.currentOp({"$all": true, "$or":[{"queryLocks":{"$exists":true}},{"lockStats":{"$exists":true}}]})
查看特定的用户:db.currentOp({"user": "yourUsername"})
查看服务器状态:db.serverStatus()
查看当前数据库连接数:db.serverStatus().connections
查看当前数据库连接IP:db.adminCommand({currentConn:1}) 阿里自研
数据一致性检查:
- 对指定集合进行数据一致性检查
db.collection_name.validate({full:true})
- 对整个数据库进行数据一致性检查:
db.runCommand({validate: "database_name", full: true}
查看内存:
- 查看mongodb实例中的连接数信息(mongos)
mongos> db.serverStatus().connections
- 查询内存相关信息:
mongos> db.serverStatus().mem
- 查看实例中wiredTiger存储引擎的cache相关信息shard>db.serverStatus().wiredTiger.cache
关注:
- 当前缓存的最大值:wiredTiger.cache.maximum bytes configured
- 当前在缓存中的数据:wiredTiger.cache.bytes currently in the cache
- wt的缓存中脏数据的大小:wiredTiger.cache.tracked dirty bytes in the cache
- 读入缓存的页数:wiredTiger.cache.pages read into cache
- 从缓存写入磁盘的数据页数:wiredTiger.cache.pages written from cache
- 动态修改wiredTiger.cach
db.adminCommand({setParameter: 1, wiredTigerEngineRuntimeConfig: "cache_size=1610612736"})
缓存大小的调整只会影响后续的读取和写入操作,不会对已经存在于缓存中的数据产生直接影响。现有的数据将继续留在缓存中,直到它们过期或被其他数据替换
查看oplog:
集群模式下,必须要要单独进入到每个具体的分片中执行操作,在每个分片上,再分别进入primary和secondary单独操作才能生效。
在每个分片的执行的操作与上述大致相同,即:
1. 查看oplog空间大小
db.printReplicationInfo()
2. 修改oplog空间大小(单台)永久生效,不用重启
db.adminCommand({replSetResizeOplog:1,minRetentionHours:8,size:51200})
3. 再次查看oplog空间大小
db.printReplicationInfo()
请求大小限制:
- 限制结果集返回大小:DBQuery.shellBatchSize = 5000
集合操作:
- 创建集合:db.createCollection("collection_name")
- 查看所有集合:show collections
- 删除集合:db.collection_name.drop()
文档操作:
- 插入文档:db.collection_name.insertOne({field1: value1, field2: value2})
- 批量插入文档:db.collection_name.insertMany([{field1: value1, field2: value2}, {field1: value3, field2: value4}])
- 查询文档:db.collection_name.find({field1: value1})
查询操作:
- 简单查询:db.collection_name.find()
- 大于某个时间段:db.promotion_report.count({ dayTime: { $gt: '2022-06-24' } })
- 正则查询:db.inventory.find( { tags: "/^red/" } )
- or查询:db.collection_name.find({$or:[{field1: value1, field2: value2}]})
- and查询:db.collection_name.find({$and:[{field1: value1, field2: value2}]})
- 条件查询:db.collection_name.find({field1: value1, field2: value2})
- 查询指定字段:db.collection_name.find({field1: 1}, {"_id":0, "compayid": 1}) /// 不返回_id字段,返回compayid
- 查询数组:db.inventory.find( { tags: ["red", "blank"] } )
- 在数组中查询元素:db.inventory.find( { tags: "red" } )
- 查询同时包含元素和 的数组:db.inventory.find( { tags: { $all: ["red", "blank"] } } )
- 查询数组包含 3 个元素的文档:db.inventory.find( { "tags": { $size: 3 } } )
- 查询排序按字段:db.collection_name.find().sort({createTime: 1}).limit(1);
- 查询排序按_id:db.el_frequent_visitor.find().sort({ '_id': -1 }).limit(1);
- 查询排序按_id并分页:db.el_frequent_visitor.find().sort({ '_id': -1 }).skip(800).limit(10);
- 查询限制:db.collection_name.find().limit(10)
- 查询跳过:db.collection_name.find().skip(5)
- 查询数据为null:db.promotion_keyword.find({ "createTime": null }).limit(10);
- 查询数据时间为字符:db.promotion_keyword.find({ "createTime": { "$lt": "2022-06-24 00:00:00" } }).
- 查询数据时间为日期:db.promotion_keyword.count({ "createTime": { "$gt": ISODate("2024-06-24T00:33:50Z") } })
- 不为空:db.js_visitor.find({ group_id: { $ne: null } })
- 为空:db.js_visitor.find({ group_id: null })
findOneAnd操作:
- db.collection.findAndModify()
- db.collection.findOneAndDelete()
- db.collection.findOneAndReplace()
- db.collection.findOneAndUpdate()
更新操作:
更新文档:db.collection_name.updateOne({field1: value1}, {$set: {field2: new_value}})
更新多个文档:db.collection_name.updateMany({field1: value1}, {$set: {field2: new_value}})
替换与指定筛选器匹配的单个文档:db.collection.replaceOne()
删除文档:
删除文档:db.collection_name.deleteOne({field1: value1});
删除多个文档:db.collection_name.deleteMany({field1: value1});
删除文档所有数据:db.collection.remove({});
聚合操作:(discint count)
聚合查询:
db.ai_scene_question.aggregate([{$group: {_id: "$sceneId",count: { $sum: 1 }}},{$match: {count: { $gt: 1 }}},{$project: {field: "$_id",count: 1,_id: 0}}])
索引操作:
- 创建索引:db.collection_name.createIndex({field1: 1, field2: -1}, {background: true})
- 查看索引:db.collection_name.getIndexes()
- 删除索引:db.collection_name.dropIndex({field1: 1, field2: -1}, {background: true})
游标:
- 查看游标:db.serverStatus().metrics.cursor
- 在会话外部打开游标:
未在会话下打开的游标会在处于非活动状态 10 分钟后自动关闭,或者客户端已用尽游标
var myCursor = db.users.find().noCursorTimeout();
cursor.close() #手动关闭光标
var myCursor = db.users.find( { type: 2 } );
myCursor
var myCursor = db.users.find( { type: 2 } );
while (myCursor.hasNext()) {
print(tojson(myCursor.next()));}
日志管理:
- 查看日志文件路径:db.adminCommand({ getParameter: 1, logComponentVerbosity: 1 })
- 打开/关闭全局日志记录:db.adminCommand({ setParameter: 1, logLevel: <level> })
- 打开/关闭特定集合的日志记录:db.setLogLevel(<level>, "command")
复制集相关:
- 查看复制集状态:rs.status()
- 查看复制集成员信息:rs.conf()
- 查看副本集同步延迟:rs.printSlaveReplicationInfo()
- 强制从节点切主:shard> db.runCommand( { replSetAbortPrimaryCatchUp: 1 })
- 分片节点添加:> rs.add("localhost:27020")
- 删除操作:> rs.remove("localhost:27017")
集群分片相关:
启动平衡器
- 停止:db.adminCommand( { balancerStop: 1 } )
- 状态:db.adminCommand( { balancerStatus: 1 } )
- 是否在迁移:sh.isBalancerRunning()
关闭某个集合的balance
- sh.disableBalancing("test.vast")
- sh.enableBalancing("test.vast")
预设定的时间做balancer
连接到其中一个mongos
use config
sh.setBalancerState( true )
// 每天3-5点
db.settings.update({ _id : "balancer" }, { $set : { activeWindow : { start : "3:00", stop : "5:00" } } }, true )
sh.getBalancerWindow() // 查看balancer时间窗口
sh.status()
查询是否存在孤立:
- mongos> db.zz1.getShardDistribution()
结果中的统计信息,查看是否存在异常或孤立的分片键。
- mongos> db.zz1.validate()
输出结果中包含类似 "Chunk is orphaned" 或 "collection is not sharded or orphaned" 的错误信息,则表示存在孤立的分片键。
输出结果中的每个分片的 details 字段。在该字段中,你可以检查分片的 orphaned 字段,如果为 true,则表示该分片存在孤立的分片键
公众号内直接回复加群,即可添加微信群。觉得帖子写的不错,点点关注,点点赞,多多转载,请多多支持。