Navigation

Monitoring

This guide shows you how to monitor topology events in a MongoDB instance, replica set, or sharded cluster. The driver creates topology events, also known as Server Discovery and Monitoring (SDAM) events, when there is a change in the state of the instance or cluster that you connected to. For example, the driver creates an event when you establish a new connection or if the cluster elects a new primary.

Read this guide if you need to record topology changes in your application or want to explore the information provided in these events.

You can access one or more SDAM 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 SDAM 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);
// 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);

You can subscribe to any of the following SDAM events:

Event NameDescription
serverOpeningCreated when a connection to an instance opens.
serverClosedCreated when a connection to an instance closes.
serverDescriptionChangedCreated when an instance state changes (such as from secondary to primary).
topologyOpeningCreated prior to attempting a connection to an instance.
topologyClosedCreated after all instance connections in the topology close.
topologyDescriptionChangedCreated when the topology changes, such as an election of a new primary or a mongos proxy disconnecting.
serverHeartbeatStartedCreated prior to issuing an isMaster command to a MongoDB instance.
serverHeartbeatSucceededCreated when the isMaster command returns successfully from a MongoDB instance.
serverHeartbeatFailedCreated when an isMaster command issued to a specific MongoDB instance fails to return a successful response

The following sections show sample output for each type of SDAM event.

ServerDescriptionChangedEvent {
topologyId: 0,
address: 'localhost:27017',
previousDescription: ServerDescription {
address: 'localhost:27017',
error: null,
roundTripTime: 0,
lastUpdateTime: 1571251089030,
lastWriteDate: null,
opTime: null,
type: 'Unknown',
minWireVersion: 0,
maxWireVersion: 0,
hosts: [],
passives: [],
arbiters: [],
tags: []
},
newDescription: ServerDescription {
address: 'localhost:27017',
error: null,
roundTripTime: 0,
lastUpdateTime: 1571251089051,
lastWriteDate: 2019-10-16T18:38:07.000Z,
opTime: { ts: Timestamp, t: 18 },
type: 'RSPrimary',
minWireVersion: 0,
maxWireVersion: 7,
maxBsonObjectSize: 16777216,
maxMessageSizeBytes: 48000000,
maxWriteBatchSize: 100000,
me: 'localhost:27017',
hosts: [ 'localhost:27017' ],
passives: [],
arbiters: [],
tags: [],
setName: 'rs',
setVersion: 1,
electionId: ObjectID,
primary: 'localhost:27017',
logicalSessionTimeoutMinutes: 30,
'$clusterTime': ClusterTime
}
}

The type field of the ServerDescription object in this event contains one of the following possible values:

TypeDescription
UnknownUnknown instance
StandaloneStandalone instance
MongosMongos proxy instance
PossiblePrimaryAt least one server recognizes this as the primary, but is not yet verified by all instances.
RSPrimaryPrimary instance
RSSecondarySecondary instance
RSArbiterArbiter instance
RSOtherSee the RSGhost specification for more details
RSGhostSee the RSOther specification for more details
ServerHeartbeatStartedEvent {
connectionId: 'localhost:27017'
}
ServerHeartbeatSucceededEvent {
duration: 1.939997,
reply:{
hosts: [ 'localhost:27017' ],
setName: 'rs',
setVersion: 1,
ismaster: true,
secondary: false,
primary: 'localhost:27017',
me: 'localhost:27017',
electionId: ObjectID,
lastWrite: {
opTime: { ts: [Timestamp], t: 18 },
lastWriteDate: 2019-10-16T18:38:17.000Z,
majorityOpTime: { ts: [Timestamp], t: 18 },
majorityWriteDate: 2019-10-16T18:38:17.000Z
},
maxBsonObjectSize: 16777216,
maxMessageSizeBytes: 48000000,
maxWriteBatchSize: 100000,
localTime: 2019-10-16T18:38:19.589Z,
logicalSessionTimeoutMinutes: 30,
minWireVersion: 0,
maxWireVersion: 7,
readOnly: false,
ok: 1,
operationTime: Timestamp,
'$clusterTime': ClusterTime
},
connectionId: 'localhost:27017'
}
ServerHeartbeatFailed {
duration: 20,
failure: MongoError('some error'),
connectionId: 'localhost:27017'
}
ServerOpeningEvent {
topologyId: 0,
address: 'localhost:27017'
}
ServerClosedEvent {
topologyId: 0,
address: 'localhost:27017'
}
TopologyOpeningEvent {
topologyId: 0
}
TopologyClosedEvent {
topologyId: 0
}
TopologyDescriptionChangedEvent {
topologyId: 0,
previousDescription: TopologyDescription {
type: 'ReplicaSetNoPrimary',
setName: null,
maxSetVersion: null,
maxElectionId: null,
servers: Map {
'localhost:27017' => ServerDescription
},
stale: false,
compatible: true,
compatibilityError: null,
logicalSessionTimeoutMinutes: null,
heartbeatFrequencyMS: 10000,
localThresholdMS: 15,
options: Object,
error: undefined,
commonWireVersion: null
},
newDescription: TopologyDescription {
type: 'ReplicaSetWithPrimary',
setName: 'rs',
maxSetVersion: 1,
maxElectionId: null,
servers: Map {
'localhost:27017' => ServerDescription
},
stale: false,
compatible: true,
compatibilityError: null,
logicalSessionTimeoutMinutes: 30,
heartbeatFrequencyMS: 10000,
localThresholdMS: 15,
options: Object,
error: undefined,
commonWireVersion: 7
}
}

The type field of the TopologyDescription object in this event contains one of the following possible values:

TypeDescription
SingleStandalone instance
ReplicaSetWithPrimaryReplica set with a primary
ReplicaSetNoPrimaryReplica set with no primary
ShardedSharded cluster
UnknownUnknown topology
Give Feedback