You can retrieve details about the queries that were run in the past 7 days using $queryHistory (aggregation). $queryHistory returns documents, one per query, that contain information about the aggregate, find, and count queries that were run in the past 7 days. You can filter on the fields returned by $queryHistory in subsequent pipeline stages such as $match.
To run $queryHistory, use the db.aggregate() helper. Run $queryHistory against the admin database.
Sintaxe
{ $queryHistory: { allUsers: <boolean> } }
Campos
Campo | Tipo | Descrição | necessidade |
|---|---|---|---|
| booleano | Indica se deve ou não buscar documentos para queries executadas por todos os usuários. Os valores válidos são:
É necessário ter o privilégio Se omitido, o padrão é | Opcional |
Saída
Cada documento retornado por $queryHistory contém os seguintes campos:
Campo | Tipo | Descrição |
|---|---|---|
| string | Nome do aplicativo que emitiu a query, se disponível. |
| booleano | Sinalizador que indica se a query foi executada em segundo plano. O valor pode ser um dos seguintes:
|
| string | Nome da collection na qual a query foi executada. |
| string | Comentário associado à query, se disponível. Vazio se a consulta não incluiu nenhum comentário. |
| string | Nome do banco de dados que contém a collection na qual a query foi executada. |
| Tempo de conclusão da query. | |
| string | Erro, se houver, retornado pela query. Observe que o status da query |
| int | Status da query. O valor pode ser um dos seguintes:
|
| Unique identifier of the operation associated with the query in the ObjectId format. The field value is the same as the | |
| Horário de início da query. | |
| documento | Operação da query que foi executada. |
| string | Nome de usuário do usuário que executou a query, se disponível, no seguinte formato: |
Exemplos
Os exemplos abaixo usam a collection Database0.Collection0 descrita no tutorial de Introdução.
Recuperar detalhes sobre as queries
No exemplo abaixo, suponha que algumas das queries descritas no tutorial de Introdução tenham sido executadas por user1 na collection Collection0 do banco de dados Database0. O exemplo abaixo retorna informações sobre as queries que foram executadas por user1 na collection Database0.Collection0.
db.aggregate([{$queryHistory: {}}]).pretty()
$queryHistory retorna um documento para cada query executada na collection Database0.Collection0.
{ "_id" : ObjectId("613fa06cf9521f85777d5be8"), "query" : [ { "$match" : { "bedrooms" : 3, "review_scores.review_scores_rating" : { "$gt" : 79 } } }, { "$count" : "numProperties" } ], "appName" : "MongoDB Shell", "user" : "admin.user1", "db" : "Database0", "collection" : "Collection0", "opid" : ObjectId("16a476f40ac6d97f22e4aa1f"), "startTime" : ISODate("2021-09-13T19:02:35.589Z"), "endTime" : ISODate("2021-09-13T19:03:08.730Z"), "ok" : 1, "background" : false } { "_id" : ObjectId("613fa0d4f9521f85777d6bc0"), "query" : [ { "$match" : { "bedrooms" : 3 } }, { "$sort" : { "review_scores_rating" : -1 } }, { "$limit" : NumberLong(5) } ], "appName" : "MongoDB Shell", "user" : "admin.user1", "db" : "Database0", "collection" : "Collection0", "opid" : ObjectId("16a4770e387f300c22e4bdf2"), "startTime" : ISODate("2021-09-13T19:04:28.184Z"), "endTime" : ISODate("2021-09-13T19:04:52.898Z"), "ok" : 1, "background" : false } { "_id" : ObjectId("613fa0eef9521f85777d6f6f"), "query" : [ { "$match" : { "limit" : { "$eq" : 10000 }, "products" : "Commodity" } }, { "$limit" : NumberLong(5) } ], "appName" : "MongoDB Shell", "user" : "admin.user1", "db" : "Database0", "collection" : "Collection0", "opid" : ObjectId("16a477163555e4aa22e4c53b"), "startTime" : ISODate("2021-09-13T19:05:02.342Z"), "endTime" : ISODate("2021-09-13T19:05:18.774Z"), "ok" : 1, "background" : false } { "_id" : ObjectId("613fa147f9521f85777d7b11"), "query" : [ { "$match" : { "name" : /Lannister/ } }, { "$limit" : NumberLong(10) } ], "appName" : "MongoDB Shell", "user" : "admin.user1", "db" : "Database0", "collection" : "Collection0", "opid" : ObjectId("16a4771ba072c0a122e4c9bd"), "startTime" : ISODate("2021-09-13T19:05:25.736Z"), "endTime" : ISODate("2021-09-13T19:06:47.147Z"), "ok" : 1, "background" : false } { "_id" : ObjectId("613fb9eccaba4e6430c7dcb7"), "query" : [ { "$group" : { "_id" : "$movies", "Collection0" : { "$push" : "$title" } } }, { "$out" : { "atlas" : { "projectId" : "{PROJECT_ID}", "clusterName" : "mySbx", "db" : "my_test", "coll" : "sample" } } } ], "appName" : "MongoDB Shell", "user" : "admin.user1", "db" : "admin", "collection" : "Collection0", "opid" : ObjectId("16a47ceba943e9cc00c98c62"), "startTime" : ISODate("2021-09-13T20:51:56.617Z"), "endTime" : ISODate("2021-09-13T20:51:56.642Z"), "ok" : 1, "background" : true }
Filtrar a saída $queryHistory para queries específicas
No exemplo a seguir, executamos uma query semelhante à seguinte Database0.Collection0 na collection descrita no tutorial de Introdução.
The query includes unique strings to help identify the query in the results returned by the $queryHistory stage. You can attach a comment to a query using the aggregate command comment option.
use Database0 db.Collection0.aggregate([ { $match: {"account_id": 557378}},{$sort: {"transactions.symbol": -1}} ],{"comment":"exampleQuery"})
To retrieve the query history using the string value of the comment option of the aggregate command, run the following commands against the admin database:
use admin db.aggregate([{$queryHistory: {}}, {$match: {"comment": "exampleQuery"}} ])
$queryHistory encontra a query que incluiu a string especificada e retorna resultados semelhantes ao exemplo a seguir:
[ { "_id": ObjectId("61e1e4c29e62172566d8e9b6"), "query": [ { "$match": { "account_id": 557378} }, { "$sort": { "transactions.symbol": -1 } } ], "comment": "exampleQuery", "appName": "mongosh 1.1.8", "user": "admin.user1", "db": "Database0", "collection": "Collection0", "opid": ObjectId("16ca3ed2577016e68d60358c"), "startTime": ISODate("2022-01-14T21:01:27.346Z"), "endTime": ISODate("2022-01-14T21:01:54.627Z"), "ok": 1, "error": "", "background": false, } ]