matteofigus matteofigus - 4 months ago 24
Node.js Question

Retrieve which replica instance was used for mongo query using node.js

I use the official node.js mongodb client for performing Mongo queries targeting a cluster via a connection string similar to:

. As you see, I include in my cluster some differently geo-located instances and "nearest" should guarantee the right replica to be picked.

Nevertheless, I would like to know which one was used to perform any query, so that I can include to each of my operations' log the mongo replica that was used to perform the query.

Hacking around the Cursor object, I can get what I want in an hacky way:

const find = (query, callback) => {

let cursor = coll.find(query);
cursor.toArray((err, items) => {
callback(err, items);

But I feel like this can break in any moment as not documented + it seems limited to the Cursor interactions (so I wouldn't know how to achieve the same for a

Is anyone aware about a clean way to do this?


You might be interested in using the APM interface.

This lets you access the context of each operation being run by the driver and is really meant for APM providers but if you want to keep track or log how your ops are executing it might be useful for you.

var listener = require('mongodb').instrument({
  operationIdGenerator: {
    operationId: 1,

    next: function() {
      return this.operationId++;

  timestampGenerator: {
    current: function() {
      return new Date().getTime();

    duration: function(start, end) {
      return end - start;
}, function(err, instrumentations) {
  // Instrument the driver  

listener.on('started', function(event) {
  // command start event (see

listener.on('succeeded', function(event) {
  // command success event (see

listener.on('failed', function(event) {
  // command failure event (see