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
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.
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.
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.
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.
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
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...
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With