文档菜单
文档首页
/ / /
Node.js 驱动程序
/ /

命令监控

在本页

  • 概述
  • 事件订阅示例
  • 事件说明
  • 示例事件文档

本指南向您展示了如何监控驱动程序发送到您的MongoDB部署的命令的成功或失败情况。

以下部分演示了如何在您的应用程序中记录命令状态,并探索这些事件提供的信息。

您可以通过在应用程序中订阅这些事件来访问一个或多个命令监控事件。以下示例演示了连接到副本集并订阅MongoDB部署创建的其中一个命令监控事件。

/* Subscribe to an event */
const { MongoClient } = require("mongodb");
// Replace the following with your MongoDB deployment's connection string
const uri = "mongodb+srv://<clusterUrl>/?replicaSet=rs&writeConcern=majority";
const client = new MongoClient(uri, { monitorCommands:true });
// Replace <event name> with the name of the event you are subscribing to
const eventName = "<event name>";
// Subscribe to a specified event and print a message when the event is received
client.on(eventName, event => console.log(event));
async function run() {
try {
// Establish and verify connection to the "admin" database
await client.db("admin").command({ ping: 1 });
console.log("Connected successfully");
} finally {
// Close the database connection on completion or error
await client.close();
}
}
run().catch(console.dir);

注意

命令监控默认是禁用的。要启用命令监控,请将monitorCommands选项作为true传递给您的MongoClient构造函数。

您可以订阅以下任何命令监控事件

事件名称
描述
commandStarted
当命令启动时创建。
commandSucceeded
当命令成功时创建。
commandFailed
当命令失败时创建。

以下部分显示了每种命令监控事件的示例输出。

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: 15,
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: 11
}

返回

集群