Wednesday, October 19, 2016

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

Leave a Comment

I use the official node.js mongodb client for performing Mongo queries targeting a cluster via a connection string similar to: mongodb://euwest1-01,euwest1-02,uswest2-01/dbname?replicaSet=mycluster&readPreference=nearest. 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) => {       console.log(cursor.server.ismaster.me);       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 findOne method).

Is anyone aware about a clean way to do this?

2 Answers

Answers 1

I suppose that it is not the best solution, but you can use the .eval() function to create a function which return server_info & result, like this:

db.getCollection('mycollection').eval(function construct(){     var res = db.getCollection('mycollection').find(query);     var explain = res.explain()['server'];     return {'server':explain,'result':res.toArray()}; })() 

which return something like :

{    "server" : "myservernode.mydomain:27017",    "result" : [         // your query results    ] } 

Answers 2

Here are some methods to determine which replica set was used for the query

This documentation might be able to help you.

It specifies how you can tail the oplog of the sharded clusters and can use find to specify which operation is used to modift the data in which cluster

To get the primary server IP you can use the following command line

rs.status().members.find() //add a query or any of your variables 

Documentation referred as here.

If You Enjoyed This, Take 5 Seconds To Share It

0 comments:

Post a Comment