Command Monitoring
On this page
Overview
This guide shows you how to use the Go driver to monitor the outcome of commands that the driver sends to your MongoDB deployment.
You might use information about command events in your application to understand changes in query performance or resolve bottlenecks.
Subscribe to Events
You can access details about command events by subscribing to them
in your application. The following example demonstrates how to subscribe
to the CommandStartedEvent
event by instantiating a
CommandMonitor
and connecting to a deployment:
var eventArray []*event.CommandStartedEvent cmdMonitor := &event.CommandMonitor{ Started: func(ctx context.Context, e *event.CommandStartedEvent) { eventArray = append(eventArray, e) }, } clientOpts := options.Client().ApplyURI(uri).SetMonitor(cmdMonitor) client, err := mongo.Connect(clientOpts)
Event Descriptions
You can subscribe to one or more of the following command monitoring events:
Event Name | Description |
---|---|
CommandStartedEvent | Created when a command starts. |
CommandSucceededEvent | Created when a command succeeds. |
CommandFailedEvent | Created when a command does not succeed. |
Example Event Documents
The following sections show sample output for each type of command monitoring event.
CommandStartedEvent
*event.CommandStartedEvent { "Command": "...", "DatabaseName": "...", "CommandName": "...", "RequestID": ..., "ConnectionID": "...", "ServerConnectionID": ..., "ServiceID": "..." }
CommandSucceededEvent
*event.CommandSucceededEvent { "DurationNanos": 38717583, "Duration": 38717583, "CommandName": "insert", "RequestID": 13, "ConnectionID": "...", "ServerConnectionID": ..., "ServiceID": null, "Reply": "..." }
CommandFailedEvent
*event.CommandFailedEvent { "DurationNanos": 38717583, "Duration": 38717583, "CommandName": "insert", "RequestID": 13, "ConnectionID": "...", "ServerConnectionID": ..., "ServiceID": null, "Failure": "..." }
Additional Information
To learn more about monitoring a MongoDB deployment, see the How to Monitor MongoDB article.
To learn more about performing MongoDB operations, see the CRUD Operations guides.
API Documentation
To learn more about the methods and types mentioned in this guide, see the following API documentation:
CommandMonitor type
SetMonitor() method
CommandStartedEvent type
CommandFailedEvent type