One liner to find a shard in a MongoDB cluster

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.

Add new comment

The content of this field is kept private and will not be shown publicly.
  • No HTML tags allowed.
  • External and mailto links in content links have an icon.
  • Lines and paragraphs break automatically.
  • Web page addresses and email addresses turn into links automatically.
  • Use [fn]...[/fn] (or <fn>...</fn>) to insert automatically numbered footnotes.
  • Each email address will be obfuscated in a human readable fashion or, if JavaScript is enabled, replaced with a spam resistent clickable link. Email addresses will get the default web form unless specified. If replacement text (a persons name) is required a webform is also required. Separate each part with the "|" pipe symbol. Replace spaces in names with "_".
About the bookAbout this siteAcademicAmazonBeginnersBooksBuildBotBusiness modelsbzrCassandraCloudcloud computingclsCommunitycommunityleadershipsummitConsistencycoodiaryCopyrightCreative CommonscssDatabasesdataminingDatastaxDevOpsDrizzleDrupalEconomyelectronEthicsEurovisionFacebookFrosconFunnyGaleraGISgithubGnomeGovernanceHandlerSocketHigh AvailabilityimpressionistimpressjsInkscapeInternetJavaScriptjsonKDEKubuntuLicensingLinuxMaidanMaker cultureMariaDBmarkdownMEAN stackMepSQLMicrosoftMobileMongoDBMontyProgramMusicMySQLMySQL ClusterNerdsNodeNoSQLodbaOpen ContentOpen SourceOpenSQLCampOracleOSConPAMPPatentsPerconaperformancePersonalPhilosophyPHPPiratesPlanetDrupalPoliticsPostgreSQLPresalespresentationsPress releasesProgrammingRed HatReplicationSeveralninesSillySkySQLSolonSunSybaseSymbiansysbenchtalksTechnicalTechnologyThe making ofTungstenTwitterUbuntuvolcanoWeb2.0WikipediaWork from HomexmlYouTube