Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

shell script - check mongod server is running

Tags:

shell

mongodb

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
like image 709
Shengjie Avatar asked May 14 '13 11:05

Shengjie


People also ask

How do you check if MongoDB server is running or not?

systemctl status mongod: Displays the same status of MongoDB service as like above command as shown in figure 1. pgrep mongo: Prints the process ID of running mongo instance. pgrep command looks through the list of running processes and list down the process ids based on name.

How do I know if my MongoDB server is running Linux?

MongoDB installs as a systemd service, which means that you can manage it using standard systemd commands alongside all other sytem services in Ubuntu. To verify the status of the service, type: sudo systemctl status mongodb.

How do you verify that MongoDB has started successfully?

Open the command prompt and type “cd c:\program files\mongodb\server\your version\bin”. After you enter the bin folder type “mongo start”. If you get either a successful connection or failed one it means it's installed at least.

How do you check if I have MongoDB shell?

Another way to get the mongo shell version is to run mongo --help from a Terminal window or Command Prompt. Result: MongoDB shell version v4.


2 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
like image 184
WiredPrairie Avatar answered Oct 11 '22 13:10

WiredPrairie


try running this in your shell script:-

pgrep mongod

If the value is numeric you know that the process is running, if you get an empty value, flag it as service not running...

like image 44
Vinu Joseph Avatar answered Oct 11 '22 13:10

Vinu Joseph