Docs Menu
Docs Home
/ / /
Node.js Driver
/ /

Command Monitoring

On this page

  • Overview
  • Event Subscription Example
  • Event Descriptions
  • Example Event Documents

This guide shows you how to monitor the success or failure of commands sent by the driver to your MongoDB deployment.

The following sections demonstrate how to record command status in your application and 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:

/* 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);

Note

Command monitoring is disabled by default. To enable command monitoring, pass the monitorCommands option as true to your MongoClient constructor.

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: 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
}

Back

Clusters