6
Jul

Shell script to identify primary from mongodb replica set and connect

I have a mongoDB 3 nodes replica setup where 1 is primary and others are secondary. If primary goes down or has some issues then one of a secondary becomes primary. JDBC drivers automatically detect primary and connect to it.

But what if a shell script in a cron needs to connect to primary, then I have to identify primary every time before connection. Below shell script can be used for the same purpose.

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
#!/bin/bash
 
user=user
pass='pass'
 
#IPs or names of replica set members
rMembers=(10.10.10.11 10.10.10.12 10.10.10.13)
 
# Identify master
for host in ${rMembers[@]}; do
  master=$host
  isMaster=$(mongo -u $user --host $host -p $pass --authenticationDatabase db_name --quiet --eval 'db.isMaster().ismaster')
  if [ "$isMaster" == "true" ]; then
    echo ""
    echo "--------------------"
    echo "Master db is $master"
    echo "--------------------"
    echo ""
    break
  fi
done
 
# Check if none of them are master, this is very rare situation when primary is failed and secondary to primary transition is in progress
if [ "$isMaster" != "true" ]; then
  echo "No master found"
  exit 1
fi
 
# Connect to master
mongo -u $user --host $master -p $pass --authenticationDatabase db_name db_name