shell script - check mongod server is running

I have a shell script to do some mongo db actions:

e.g. mongo testdb --eval "db.dropDatabase()"

BUT, if the mongod server is not running, I get:

MongoDB shell version: 2.0.4
connecting to: testdb
Tue May 14 04:33:58 Error: couldn't connect to server 127.0.0.1 shell/mongo.js:84

Is there a way in mongo I can check the connection status? Eventually I want something like:

if(mongod is running):
    mongo testdb --eval "db.dropDatabase()"
else:
    echo "pls make sure your mongod is running"
    exit 1

Answers


You should be able to create a bash script like this:

mongo --eval "db.stats()"  # do a simple harmless command of some sort

RESULT=$?   # returns 0 if mongo eval succeeds

if [ $RESULT -ne 0 ]; then
    echo "mongodb not running"
    exit 1
else
    echo "mongodb running!"
fi

this is what i run to check if mongod is up:

# this script checks if the mongod is running.
# if not, send mail
#

EMAILIST=dba@wherever



`ps -A | grep -q '[m]ongod'`

if [ "$?" -eq "0" ]; then
    exit 0
else
    echo "The mongod server SB2MDB01 is DOWN" | mailx \
    -s "Server DOWN: SB2MDB01" $EMAILIST
fi

exit 0

Need Your Help

Saving data to a new table with CakePHP

php mysql cakephp

I have an order database and wish to save the orders in a new database once the order is completed. My Order model has a table with id, customer, partnumber etc. and my OldOrder has a copy of the O...

About UNIX Resources Network

Original, collect and organize Developers related documents, information and materials, contains jQuery, Html, CSS, MySQL, .NET, ASP.NET, SQL, objective-c, iPhone, Ruby on Rails, C, SQL Server, Ruby, Arrays, Regex, ASP.NET MVC, WPF, XML, Ajax, DataBase, and so on.