Docs Home → Develop Applications → MongoDB Drivers → Node.js
Command Monitoring
Overview
This guide shows you how to monitor the success or failure of commands sent by the driver to your MongoDB deployment.
Read this guide if you need to record command status in your application or want to explore the information provided in these events.
Event Subscription Example
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:
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>"; 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);
Note
Command monitoring is disabled by default. To enable command
monitoring, pass the monitorCommands
option as true
to
your MongoClient
constructor.
Event Descriptions
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. |
Example Event Documents
The following sections show sample output for each type of command monitoring event.
commandStarted
CommandStartedEvent { requestId: 1534, databaseName: "app", commandName: "find", address: 'localhost:27017', connectionId: 812613, command: { find: { firstName: "Jane", lastName: "Doe" } } }
commandSucceeded
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 } }
commandFailed
CommandFailedEvent { requestId: 1534, commandName: "find", address: 'localhost:27017', connectionId: 812613, failure: Error("something failed"), duration: 1586380205 }