Command Monitoring命令监视

This guide shows you how to monitor the success or failure of commands sent by the driver to your MongoDB deployment.本指南向您展示了如何监控驱动程序发送到MongoDB部署的命令的成功或失败。

Read this guide if you need to record command status in your application or want to explore the information provided in these events.如果您需要在应用程序中记录命令状态,或者希望了解这些事件中提供的信息,请阅读本指南。

You can access one or more command monitoring events using the driver by subscribing to them in your application. 通过在应用程序中订阅,可以使用驱动程序访问一个或多个命令监视事件。The following example demonstrates connecting to a replica set and subscribing to one of the command monitoring events created by the MongoDB deployment:以下示例演示如何连接到副本集并订阅MongoDB部署创建的命令监视事件之一:

const { MongoClient } = require("mongodb");
// Replace the following with your MongoDB deployment's connection string.用MongoDB部署的连接字符串替换以下内容。 const uri = "mongodb+srv://<clusterUrl>/?replicaSet=rs&writeConcern=majority";
const client = new MongoClient(uri);
// Replace <event name> with the name of the event you are subscribing to.使用您要订阅的事件的名称替换<event name>。 const eventName = "<event name>"; client.on(eventName, event=> { console.log(`received${eventName}:${JSON.stringify(event,null,2)}`); });
async function run(){ try { await client.connect();
// Establish and verify connection await client.db("admin").command({ ping: 1 }); console.log("Connected successfully"); } finally { // Ensures that the client will close when you finish/error确保完成/出错时客户端将关闭 await client.close(); } } run().catch(console.dir);

You can subscribe to any of the following command monitoring events:您可以订阅以下任何命令监视事件:

Event Name事件名称
Description描述
commandStarted
Created when a command is started.在命令启动时创建。
commandSucceeded
Created when a command succeeded.在命令成功时创建。
commandFailed
Created when a command failed.在命令失败时创建。

The following sections show sample output for each type of command monitoring event.以下各节显示了每种类型的命令监视事件的示例输出。

CommandStartedEvent {
  requestId: 1534,
  databaseName: "app",
  commandName: "find",
  address: 'localhost:27017',
  connectionId: 812613,
  command: {
    find: { firstName: "Jane", lastName: "Doe" }
  }
}
CommandSucceededEvent {
  requestId: 1534,
  commandName: "find",
  address: 'localhost:27017',
  connectionId: 812613,
  duration: 1586380205,
  reply: {
    cursor: {
      firstBatch: [
        {
          _id: ObjectId("5e8e2ca217b5324fa9847435"),
          firstName: "Jane",
          lastName: "Doe"
        }
      ],
      _id: 0,
      ns: "app.users"
    },
    ok: 1,
    operationTime: 1586380205
  }
}
CommandFailedEvent {
  requestId: 1534,
  commandName: "find",
  address: 'localhost:27017',
  connectionId: 812613,
  failure: Error("something failed"),
  duration: 1586380205
}