Docs 菜单
Docs 主页
/ / /
Node.js 驱动程序
/ /

命令监控

在此页面上

  • Overview
  • 事件订阅示例
  • 事件描述
  • 示例事件文档

本指南向您展示如何监控驱动程序向 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
}

后退

集群