【随笔记】MongoDB - 了解应用的动态

1、了解正在进行的操作

> db.currentOp()
{
        "inprog" : [
                {
                        "desc" : "conn3", // 与日志信息联系
                        "threadId" : "140223308420864",
                        "connectionId" : 3,
                        "client" : "127.0.0.1:45978", // 操作来源
                        "appName" : "MongoDB Shell",
                        "clientMetadata" : {
                                "application" : {
                                        "name" : "MongoDB Shell"
                                },
                                "driver" : {
                                        "name" : "MongoDB Internal Client",
                                        "version" : "3.4.15"
                                },
                                "os" : {
                                        "type" : "Linux",
                                        "name" : "CentOS Linux release 7.5.1804 (Core) ",
                                        "architecture" : "x86_64",
                                        "version" : "Kernel 3.10.0-862.el7.x86_64"
                                }
                        },
                        "active" : true, // 是否正在运行
                        "opid" : 778, // 操作唯一标识,通过它终止一个操作
                        "secs_running" : 0, // 已经执行的时间
                        "microsecs_running" : NumberLong(93),
                        "op" : "command", // 操作的类型:查询、插入、更新、删除;
                        "ns" : "admin.$cmd",
                        "query" : {
                                "currentOp" : 1
                        },
                        "numYields" : 0, // 该操作交出锁而使其他操作得以运行的次数
                        "locks" : { // 该操作使用的锁类型,"^"表示全局锁

                        },
                        "waitingForLock" : false, // 表示该操作是否因为正在等待其他操作交出锁而处于阻塞状态
                        "lockStats" : { // lockStats.timeAcquiringMicros 表示该操作需要多长时间才能取得所需的锁

                        }
                }
        ],
        "ok" : 1
}

对于currentOp中的任何字段都可以进行查询,如 db.currentOp({"secs_running": {"$gte": 100}})

根据查找到的opid终止操作的执行

db.killOp(778)

一般只有交出了锁的进程才能被终止,正在占用锁或等待交出锁的操作无法被终止;

忽略用于复制的线程和分片中用于回写的监听器,local.oplog.rs长时间运行请求等;

组织幽灵写入最好方式是使用应答式写入,即每次写入操作都会等待上一次写入操作完成后才进行下去,而非在上一次写入进入数据库服务器的缓存区就开始下一次写入;

2、系统分析器system profiler

可查找耗时过长的操作,但开销较大,所以可以定期打开分析器来获取信息;

开启分析器
数据库收到的所有读写请求都将被记录在当前数据库的system.profile集合中;

级别为“2”级,分析器会记录所有内容;
级别为“1”级,只记录长耗时操作,默认时间为100ms,自定义耗时标准,作为第二个参数传入setProfilingLevel()函数即可;
级别为“0”级,关闭分析器;

> use mydb
switched to db mydb
> db.setProfilingLevel(2)
{ "was" : 0, "slowms" : 100, "ok" : 1 }

验证分析器

> db.foo.insert({x:1})
WriteResult({ "nInserted" : 1 })
> db.foo.update({},{$set:{x:2}})
WriteResult({ "nMatched" : 1, "nUpserted" : 0, "nModified" : 1 })
> db.foo.remove({})
WriteResult({ "nRemoved" : 1 })
> db.system.profile.find().pretty()
{
        "op" : "insert",
        "ns" : "mydb.foo",
        "query" : {
                "insert" : "foo",
                "documents" : [
                        {
                                "_id" : ObjectId("5b04cf5651d72ae1f31dbfa3"),
                                "x" : 1
                        }
                ],
                "ordered" : true
        },
        "ninserted" : 1,
        "keysInserted" : 1,
        "numYield" : 0,
        "locks" : {
                "Global" : {
                        "acquireCount" : {
                                "r" : NumberLong(3),
                                "w" : NumberLong(3)
                        }
                },
                "Database" : {
                        "acquireCount" : {
                                "w" : NumberLong(2),
                                "W" : NumberLong(1)
                        }
                },
                "Collection" : {
                        "acquireCount" : {
                                "w" : NumberLong(2)
                        }
                }
        },
        "responseLength" : 29,
        "protocol" : "op_command",
        "millis" : 21,
        "ts" : ISODate("2018-05-23T02:17:58.993Z"),
        "client" : "127.0.0.1",
        "appName" : "MongoDB Shell",
        "allUsers" : [
                {
                        "user" : "root",
                        "db" : "admin"
                }
        ],
        "user" : "root@admin"
}
{
        "op" : "update",
        "ns" : "mydb.foo",
        "updateobj" : {
                "$set" : {
                        "x" : 2
                }
        },
        "keysExamined" : 0,
        "docsExamined" : 1,
        "nMatched" : 1,
        "nModified" : 1,
        "numYield" : 0,
        "locks" : {
                "Global" : {
                        "acquireCount" : {
                                "r" : NumberLong(1),
                                "w" : NumberLong(1)
                        }
                },
                "Database" : {
                        "acquireCount" : {
                                "w" : NumberLong(1)
                        }
                },
                "Collection" : {
                        "acquireCount" : {
                                "w" : NumberLong(1)
                        }
                }
        },
        "millis" : 0,
        "planSummary" : "COLLSCAN",
        "execStats" : {
                "stage" : "UPDATE",
                "nReturned" : 0,
                "executionTimeMillisEstimate" : 0,
                "works" : 3,
                "advanced" : 0,
                "needTime" : 2,
                "needYield" : 0,
                "saveState" : 0,
                "restoreState" : 0,
                "isEOF" : 1,
                "invalidates" : 0,
                "nMatched" : 1,
                "nWouldModify" : 1,
                "nInvalidateSkips" : 0,
                "wouldInsert" : false,
                "fastmodinsert" : false,
                "inputStage" : {
                        "stage" : "COLLSCAN",
                        "nReturned" : 1,
                        "executionTimeMillisEstimate" : 0,
                        "works" : 2,
                        "advanced" : 1,
                        "needTime" : 1,
                        "needYield" : 0,
                        "saveState" : 1,
                        "restoreState" : 1,
                        "isEOF" : 0,
                        "invalidates" : 0,
                        "direction" : "forward",
                        "docsExamined" : 1
                }
        },
        "ts" : ISODate("2018-05-23T02:18:12.732Z"),
        "client" : "127.0.0.1",
        "appName" : "MongoDB Shell",
        "allUsers" : [
                {
                        "user" : "root",
                        "db" : "admin"
                }
        ],
        "user" : "root@admin"
}
{
        "op" : "remove",
        "ns" : "mydb.foo",
        "keysExamined" : 0,
        "docsExamined" : 1,
        "ndeleted" : 1,
        "keysDeleted" : 1,
        "numYield" : 0,
        "locks" : {
                "Global" : {
                        "acquireCount" : {
                                "r" : NumberLong(1),
                                "w" : NumberLong(1)
                        }
                },
                "Database" : {
                        "acquireCount" : {
                                "w" : NumberLong(1)
                        }
                },
                "Collection" : {
                        "acquireCount" : {
                                "w" : NumberLong(1)
                        }
                }
        },
        "millis" : 0,
        "planSummary" : "COLLSCAN",
        "execStats" : {
                "stage" : "DELETE",
                "nReturned" : 0,
                "executionTimeMillisEstimate" : 0,
                "works" : 3,
                "advanced" : 0,
                "needTime" : 2,
                "needYield" : 0,
                "saveState" : 0,
                "restoreState" : 0,
                "isEOF" : 1,
                "invalidates" : 0,
                "nWouldDelete" : 1,
                "nInvalidateSkips" : 0,
                "inputStage" : {
                        "stage" : "COLLSCAN",
                        "nReturned" : 1,
                        "executionTimeMillisEstimate" : 0,
                        "works" : 3,
                        "advanced" : 1,
                        "needTime" : 1,
                        "needYield" : 0,
                        "saveState" : 1,
                        "restoreState" : 1,
                        "isEOF" : 1,
                        "invalidates" : 0,
                        "direction" : "forward",
                        "docsExamined" : 1
                }
        },
        "ts" : ISODate("2018-05-23T02:18:27.772Z"),
        "client" : "127.0.0.1",
        "appName" : "MongoDB Shell",
        "allUsers" : [
                {
                        "user" : "root",
                        "db" : "admin"
                }
        ],
        "user" : "root@admin"
}

记录耗时超过500ms的操作:

> db.setProfilingLevel(1, 500)
{ "was" : 2, "slowms" : 100, "ok" : 1 }

关闭分析器:

> db.setProfilingLevel(0, 100)
{ "was" : 0, "slowms" : 100, "ok" : 1 }

即使分析器处于关闭状态,“slowms”也决定哪些操作作为耗时过长的操作被记录到日志中;所以通常情况下,不要将slowms的值设置得过小,如果处于某种需求降低了slowms的值,在关闭分析器前也要将它重新调高;

> db.getProfilingLevel()
0

3、空间消耗

3.1 返回文档在磁盘上占用字节数,并未包括自动生成的空间间隔 padding和索引;
将_id存储为ObjectId类型比存储为字符串类型效率更高;

> Object.bsonsize({_id:ObjectId()})
22
> Object.bsonsize({_id:""+ObjectId()})
39
> db.foo.findOne()
{ "_id" : ObjectId("5b04d89c51d72ae1f31dbfa6"), "x" : 1 }
> Object.bsonsize(db.foo.findOne())
33

3.2 集合信息
在使用stats()时传入比例因子scale factor,KB值为1024,MB为1024*1024,依次类推;

> db.foo.stats()
{
        "ns" : "mydb.foo", // 命名空间
        "size" : 33, // 相当于对此集合中左右元素执行Object.bsonsize()再相加得到的值
        "count" : 1,
        "avgObjSize" : 33,
        "storageSize" : 16384, // 除了文档占用空间、文档间隔、索引,还包含两端预留快速添加新文档的未经使用的空间
        "capped" : false,
        "wiredTiger" : {
                "metadata" : {
                        "formatVersion" : 1
                },
                "creationString" : "access_pattern_hint=none,allocation_size=4KB,app_metadata=(formatVersion=1),block_allocation=best,block_compressor=snappy,cache_resident=false,checksum=on,colgroups=,collator=,columns=,dictionary=0,encryption=(keyid=,name=),exclusive=false,extractor=,format=btree,huffman_key=,huffman_value=,ignore_in_memory_cache_size=false,immutable=false,internal_item_max=0,internal_key_max=0,internal_key_truncate=true,internal_page_max=4KB,key_format=q,key_gap=10,leaf_item_max=0,leaf_key_max=0,leaf_page_max=32KB,leaf_value_max=64MB,log=(enabled=true),lsm=(auto_throttle=true,bloom=true,bloom_bit_count=16,bloom_config=,bloom_hash_count=8,bloom_oldest=false,chunk_count_limit=0,chunk_max=5GB,chunk_size=10MB,merge_max=15,merge_min=0),memory_page_max=10m,os_cache_dirty_max=0,os_cache_max=0,prefix_compression=false,prefix_compression_min=4,source=,split_deepen_min_child=0,split_deepen_per_child=0,split_pct=90,type=file,value_format=u",
                "type" : "file",
                "uri" : "statistics:table:collection-1--9139518473434896245",
                "LSM" : {
                        "bloom filter false positives" : 0,
                        "bloom filter hits" : 0,
                        "bloom filter misses" : 0,
                        "bloom filter pages evicted from cache" : 0,
                        "bloom filter pages read into cache" : 0,
                        "bloom filters in the LSM tree" : 0,
                        "chunks in the LSM tree" : 0,
                        "highest merge generation in the LSM tree" : 0,
                        "queries that could have benefited from a Bloom filter that did not exist" : 0,
                        "sleep for LSM checkpoint throttle" : 0,
                        "sleep for LSM merge throttle" : 0,
                        "total size of bloom filters" : 0
                },
                "block-manager" : {
                        "allocations requiring file extension" : 3,
                        "blocks allocated" : 3,
                        "blocks freed" : 0,
                        "checkpoint size" : 4096,
                        "file allocation unit size" : 4096,
                        "file bytes available for reuse" : 0,
                        "file magic number" : 120897,
                        "file major version number" : 1,
                        "file size in bytes" : 16384,
                        "minor version number" : 0
                },
                "btree" : {
                        "btree checkpoint generation" : 12,
                        "column-store fixed-size leaf pages" : 0,
                        "column-store internal pages" : 0,
                        "column-store variable-size RLE encoded values" : 0,
                        "column-store variable-size deleted values" : 0,
                        "column-store variable-size leaf pages" : 0,
                        "fixed-record size" : 0,
                        "maximum internal page key size" : 368,
                        "maximum internal page size" : 4096,
                        "maximum leaf page key size" : 2867,
                        "maximum leaf page size" : 32768,
                        "maximum leaf page value size" : 67108864,
                        "maximum tree depth" : 3,
                        "number of key/value pairs" : 0,
                        "overflow pages" : 0,
                        "pages rewritten by compaction" : 0,
                        "row-store internal pages" : 0,
                        "row-store leaf pages" : 0
                },
                "cache" : {
                        "bytes currently in the cache" : 883,
                        "bytes read into cache" : 0,
                        "bytes written from cache" : 127,
                        "checkpoint blocked page eviction" : 0,
                        "data source pages selected for eviction unable to be evicted" : 0,
                        "hazard pointer blocked page eviction" : 0,
                        "in-memory page passed criteria to be split" : 0,
                        "in-memory page splits" : 0,
                        "internal pages evicted" : 0,
                        "internal pages split during eviction" : 0,
                        "leaf pages split during eviction" : 0,
                        "modified pages evicted" : 1,
                        "overflow pages read into cache" : 0,
                        "overflow values cached in memory" : 0,
                        "page split during eviction deepened the tree" : 0,
                        "page written requiring lookaside records" : 0,
                        "pages read into cache" : 0,
                        "pages read into cache requiring lookaside entries" : 0,
                        "pages requested from the cache" : 14,
                        "pages written from cache" : 2,
                        "pages written requiring in-memory restoration" : 0,
                        "tracked dirty bytes in the cache" : 0,
                        "unmodified pages evicted" : 0
                },
                "cache_walk" : {
                        "Average difference between current eviction generation when the page was last considered" : 0,
                        "Average on-disk page image size seen" : 0,
                        "Clean pages currently in cache" : 0,
                        "Current eviction generation" : 0,
                        "Dirty pages currently in cache" : 0,
                        "Entries in the root page" : 0,
                        "Internal pages currently in cache" : 0,
                        "Leaf pages currently in cache" : 0,
                        "Maximum difference between current eviction generation when the page was last considered" : 0,
                        "Maximum page size seen" : 0,
                        "Minimum on-disk page image size seen" : 0,
                        "On-disk page image sizes smaller than a single allocation unit" : 0,
                        "Pages created in memory and never written" : 0,
                        "Pages currently queued for eviction" : 0,
                        "Pages that could not be queued for eviction" : 0,
                        "Refs skipped during cache traversal" : 0,
                        "Size of the root page" : 0,
                        "Total number of pages currently in cache" : 0
                },
                "compression" : {
                        "compressed pages read" : 0,
                        "compressed pages written" : 0,
                        "page written failed to compress" : 0,
                        "page written was too small to compress" : 2,
                        "raw compression call failed, additional data available" : 0,
                        "raw compression call failed, no additional data available" : 0,
                        "raw compression call succeeded" : 0
                },
                "cursor" : {
                        "bulk-loaded cursor-insert calls" : 0,
                        "create calls" : 2,
                        "cursor-insert key and value bytes inserted" : 102,
                        "cursor-remove key bytes removed" : 1,
                        "cursor-update value bytes updated" : 0,
                        "insert calls" : 3,
                        "next calls" : 6,
                        "prev calls" : 2,
                        "remove calls" : 1,
                        "reset calls" : 13,
                        "restarted searches" : 0,
                        "search calls" : 3,
                        "search near calls" : 2,
                        "truncate calls" : 0,
                        "update calls" : 0
                },
                "reconciliation" : {
                        "dictionary matches" : 0,
                        "fast-path pages deleted" : 0,
                        "internal page key bytes discarded using suffix compression" : 0,
                        "internal page multi-block writes" : 0,
                        "internal-page overflow keys" : 0,
                        "leaf page key bytes discarded using prefix compression" : 0,
                        "leaf page multi-block writes" : 0,
                        "leaf-page overflow keys" : 0,
                        "maximum blocks required for a page" : 0,
                        "overflow values written" : 0,
                        "page checksum matches" : 0,
                        "page reconciliation calls" : 4,
                        "page reconciliation calls for eviction" : 0,
                        "pages deleted" : 2
                },
                "session" : {
                        "object compaction" : 0,
                        "open cursor count" : 2
                },
                "transaction" : {
                        "update conflicts" : 0
                }
        },
        "nindexes" : 1, // 集合中索引的数量
        "totalIndexSize" : 16384,
        "indexSizes" : {
                "_id_" : 16384
        },
        "ok" : 1
}

3.3 数据库信息

> db.stats()
{
        "db" : "mydb", // 数据库名
        "collections" : 2, // 包含集合数目
        "views" : 0,
        "objects" : 5, // 数据库中所有集合包含的文档总数
        "avgObjSize" : 656.6,
        "dataSize" : 3283, // 数据库中的数据占用的空间大小,不包含空闲列表中的空间,但包含了文档间的间隔;该值与storageSize值的差异为被删除文档的大小
        "storageSize" : 32768, // 数据库正在使用的总空间大小
        "numExtents" : 0,
        "indexes" : 1,
        "indexSize" : 16384,
        "ok" : 1
}

猜你喜欢

转载自blog.csdn.net/hellboy0621/article/details/80415310