Esta página mostra exemplos para mongostat.
Run mongostat from the system command line, not the mongo shell.
Especifique mongostat período e frequência de coleção
In the first example, mongostat will return data every second for 20 seconds. mongostat collects data from the mongod instance running on the localhost interface on port 27017. All of the following invocations produce identical behavior:
mongostat --rowcount=20 1 mongostat --rowcount=20 mongostat -n=20 1 mongostat -n=20
In the next example, mongostat returns data every 5 minutes (or 300 seconds) for as long as the program runs. mongostat collects data from the mongod instance running on the localhost interface on port 27017. The following invocations produce identical behavior:
mongostat --rowcount=0 300 mongostat -n=0 300 mongostat 300
In the following example, mongostat returns data every 5 minutes for an hour (12 times.) mongostat collects data from the mongod instance running on the localhost interface on port 27017. The following invocations produce identical behavior:
mongostat --rowcount=12 300 mongostat -n=12 300
Adicionar campos a mongostat gera
-O allows you to specify fields from the serverStatus output to add to the default mongostat output. If you include a space in your custom filed name, do not put additional quotes around the field name.
O exemplo seguinte adiciona campos à saída mongostat padrão:
mongostat -O='host,version,network.numRequests=network requests'
A saída mongostat se assemelha a:
insert query update delete getmore command dirty used flushes vsize res qrw arw net_in net_out conn time host version network requests *0 *0 *0 *0 0 2|0 0.0% 0.0% 0 2.51G 19.0M 0|0 0|0 158b 39.4k 2 Oct 11 12:14:45.878 localhost:37017 3.3.14 91 *0 *0 *0 *0 0 1|0 0.0% 0.0% 0 2.51G 19.0M 0|0 0|0 157b 39.3k 2 Oct 11 12:14:46.879 localhost:37017 3.3.14 95 *0 *0 *0 *0 0 1|0 0.0% 0.0% 0 2.51G 19.0M 0|0 0|0 157b 39.2k 2 Oct 11 12:14:47.884 localhost:37017 3.3.14 99
Os seguintes campos são adicionados à saída padrão:
The network.numRequests field has a custom field name, "network requests".
Especifique mongostat campos de saída
-o specifies the columns mongostat includes in its output. You can specify any serverStatus field as a mongostat output column.
O exemplo a seguir utiliza campos personalizados para mongostat:
mongostat --port 27500 -o='host,opcounters.insert.rate()=Insert Rate,opcounters.query.rate()=Query Rate,opcounters.command.rate()=Command Rate,wiredTiger.cache.pages requested from the cache=Pages Req,metrics.document.inserted=inserted rate'
A saída mongostat se assemelha a:
host Insert Rate Query Rate Command Rate Pages Req Inserted Rate localhost:27500 180 1 8 2999446 9638 localhost:27500 40 3 12 2999601 9678 localhost:27500 181 2 9 3000207 9859 localhost:27500 39 2 12 3000362 9899 localhost:27500 181 2 11 3000969 10080 localhost:27500 39 2 10 3001124 10120
Os contadores e os nomes de campos personalizados correspondentes são:
Contador | Nome do campo personalizado |
|---|---|
opcounters.insert.rate | Inserir taxa |
opcounters.query.rate | Taxa de query |
opcounters.command.rate | Taxa de comando |
wiredTiger.cache.pages solicitado a partir do cache | Necessidade de páginas |
metrics.document.inserted | Taxa inserida |
Visualize a taxa de mudança de um campo com .rate()
.rate() enables you to view the rate per second at which a numerical field has changed from one mongostat call to the next. For example, you can view the rate at which documents have been inserted during an insert operation. .rate() can therefore help you view the performance of your mongod instance.
The following example reports on the rate of change of the metrics.document.inserted serverStatus field. The invocation uses -o's ability to specify the name of an column to label metrics.document.inserted.rate() as "inserted rate" and metrics.document.inserted as "inserted":
mongostat -o='host,mem,bits,metrics.document.inserted.rate()=inserted rate,metrics.document.inserted=inserted' --rowcount=5
A saída seria então semelhante a:
host mem.bits inserted rate inserted localhost:37017 64 501 3455 localhost:37017 64 967 13128 localhost:37017 64 972 22851 localhost:37017 64 214 25000 localhost:37017 64 0 25000
Visualizar alterações de campo com .diff()
.diff() returns the difference between the current serverStatus field value and the value from the previous mongostat call. The following example returns statistics on the number of documents being inserted into a collection: inserted diff is the difference in the metrics.document.inserted field between subsequent calls, while inserted is the value of metrics.document.inserted:
mongostat -o='host,mem.bits,metrics.document.inserted.diff()=inserted diff,metrics.document.inserted=inserted' --rowcount=5
A saída seria então semelhante a:
host mem.bits inserted diff inserted localhost:27017 64 0 25359 localhost:27017 64 94 25453 localhost:27017 64 938 26391 localhost:27017 64 964 27355 localhost:27017 64 978 28333
Visualizar estatísticas de um conjunto de réplica ou cluster compartilhado
In many cases, using the --discover option will help provide a more complete snapshot of the state of an entire group of machines. If a mongos process connected to a sharded cluster is running on port 27017 of the local machine, you can use the following form to return statistics from all members of the cluster:
mongostat --discover
Visualize estatísticas em uma interface interativa
Use a opção --interactive para exibir estatísticas em uma saída interativa no estilo ncurses sem rolagem. A opção --interactive permite destacar hosts, colunas ou campos específicos para visualização. Quando combinado com --discover, --interactive exibe estatísticas de todos os membros de um conjunto de réplicas ou cluster fragmentado, como no exemplo a seguir:
mongostat --discover --interactive
A saída de um cluster fragmentado se assemelharia a:
host insert query update delete getmore command dirty used flushes mapped vsize res faults qrw arw net_in net_out conn set repl time hostname.local:27018 *0 *0 *0 *0 0 1|0 0.0% 0.0% 0 3.25G 25.0M n/a 0|0 1|0 157b 43.9k 19 tic PRI Nov 2 11:44:46.439 hostname.local:27019 *0 *0 *0 *0 0 2|0 0.0% 0.0% 0 3.18G 26.0M n/a 0|0 1|0 322b 44.4k 12 tic SEC Nov 2 11:44:46.439 hostname.local:27020 *0 *0 *0 *0 0 2|0 0.0% 0.0% 0 3.18G 26.0M n/a 0|0 1|0 322b 44.4k 12 tic SEC Nov 2 11:44:46.439 hostname.local:27021 2017 *0 *0 *0 826 1029|0 0.0% 0.0% 0 3.25G 31.0M n/a 0|0 1|0 1.74m 1.60m 20 tac PRI Nov 2 11:44:46.439 hostname.local:27022 *2021 *0 *0 *0 0 2|0 0.0% 0.0% 0 3.19G 32.0M n/a 0|0 1|0 322b 44.6k 12 tac SEC Nov 2 11:44:46.438 hostname.local:27023 *2022 *0 *0 *0 0 3|0 0.0% 0.0% 0 3.19G 33.0M n/a 0|0 1|0 323b 44.7k 12 tac SEC Nov 2 11:44:46.438 localhost:27017 2071 *0 *0 *0 0 2073|0 0 0B 2.43G 9.00M 0 0|0 0|0 249k 130k 4 RTR Nov 2 11:44:47.429 Press '?' to toggle help
Conecte-se a um cluster MongoDB Atlas usando as credenciais AWS IAM
Novidades na versão 100.1.0.
Para conectar a um agrupamento do MongoDB Atlas que foi configurado para suportar autenticação via Credenciais AWS IAM, forneça um connection string a mongostat semelhante ao seguinte:
mongostat 'mongodb+srv://<aws access key id>:<aws secret access key>@cluster0.example.com/testdb?authSource=$external&authMechanism=MONGODB-AWS' <other options>
Connecting to Atlas using AWS IAM credentials in this manner uses the MONGODB-AWS authentication mechanism and the $external authSource, as shown in this example.
Se estiver usando um token de sessão da AWS, forneça-o também com o valor AWS_SESSION_TOKEN authMechanismProperties, como segue:
mongostat 'mongodb+srv://<aws access key id>:<aws secret access key>@cluster0.example.com/testdb?authSource=$external&authMechanism=MONGODB-AWS&authMechanismProperties=AWS_SESSION_TOKEN:<aws session token>' <other options>
Observação
Se o ID da chave de acesso da AWS, a chave de acesso secreta ou o token de sessão incluírem os seguintes caracteres:
: / ? # [ ] @
esses caracteres devem ser convertidos usando codificação percentual.
Como alternativa, a ID da chave de acesso da AWS, a chave de acesso secreta e, opcionalmente, o token de sessão podem ser fornecidos fora da string de conexão usando as opções --username, --password e --awsSessionToken, desta forma:
mongostat 'mongodb+srv://cluster0.example.com/testdb?authSource=$external&authMechanism=MONGODB-AWS' --username <aws access key id> --password <aws secret access key> --awsSessionToken <aws session token> <other options>
Quando fornecidos como parâmetros da linha de comando, estas três opções não exigem codificação percentual.
Você também pode definir essas credenciais em sua plataforma usando variáveis de ambiente padrão do AWS IAM. mongostat verifica as seguintes variáveis de ambiente quando você usa o MONGODB-AWS authentication mechanism:
AWS_ACCESS_KEY_IDAWS_SECRET_ACCESS_KEYAWS_SESSION_TOKEN
Se definidas, essas credenciais não precisam ser especificadas na connection string ou por meio de suas opções explícitas.
Observação
Se você optar por usar as variáveis de ambiente da AWS para especificar esses valores, não poderá combinar e corresponder com as opções explícitas ou de cadeia de conexão correspondentes para essas credenciais. Use as variáveis de ambiente para ID de chave de acesso e chave de acesso secreta (e token de sessão, se usado) ou especifique cada uma delas usando as opções explícitas ou de cadeia de conexão.
O exemplo a seguir define essas variáveis de ambiente no shell bash :
export AWS_ACCESS_KEY_ID='<aws access key id>' export AWS_SECRET_ACCESS_KEY='<aws secret access key>' export AWS_SESSION_TOKEN='<aws session token>'
A sintaxe para definir variáveis de ambiente em outros shells será diferente. Consulte a documentação da sua plataforma para obter mais informações.
Você pode verificar se essas variáveis de ambiente foram definidas com o seguinte comando:
env | grep AWS
Depois de definido, o exemplo a seguir se conecta a um MongoDB Atlas cluster usando estas variáveis de ambiente:
mongostat 'mongodb+srv://cluster0.example.com/testdb?authSource=$external&authMechanism=MONGODB-AWS' <other options>