One liner to find a shard in a MongoDB cluster

hingo's picture

I occasionally post so called "one liners", shell commands that can be used to filter out some data I need. The main reason I do this is that I can later find this when I try to google for it. This will be my first one liner for MongoDB. Ok, so it is actually 3 related one liners.

If you need to find out if a shard is already part of your MongoDB cluster, try this:


MONGOS="ec2-54-228-106-184.eu-west-1.compute.amazonaws.com"
echo "db.shards.find()" | mongo $MONGOS/config | grep Shard4 | wc -l

The result will be either 1 or 0.

Now, if the shard exists, you might want to know a hostname and port number of one of the members of that replicaset:


echo 'db.shards.find( { "_id" : "Shard4" }, { "host" : true, "_id" : false } )' | mongo $MONGOS/config | grep Shard4 | awk -F":" '{ print $2}' | awk -F"/" '{print $2}'
ec2-54-246-27-205.eu-west-1.compute.amazonaws.com


echo 'db.shards.find( { "_id" : "Shard4" }, { "host" : true, "_id" : false } )' | mongo $MONGOS/config | grep Shard4 | awk -F":" '{ print $3}' | awk -F"," '{print $1}'
27017

This is useful when you try to deploy MongoDB clusters with some automated tooling or AWS autoscaling.

Post new comment

The content of this field is kept private and will not be shown publicly.
  • Use [fn]...[/fn] (or <fn>...</fn>) to insert automatically numbered footnotes.
  • Allowed HTML tags: <h1> <h2> <h3> <h4> <p> <a> <em> <strong> <cite> <code> <ul> <ol> <li> <dl> <dt> <dd> <br> <sup> <div> <blockquote> <pre> <img>
  • Lines and paragraphs break automatically.
  • Web page addresses and e-mail addresses turn into links automatically. (Better URL filter.)

CAPTCHA
This question is for testing whether you are a human visitor and to prevent automated spam submissions.
17 + 1 =
Solve this simple math problem and enter the result. E.g. for 1+3, enter 4.