Using Ubuntu 18.04. I have the following bash script to install and run the MongoDB. IT checks if MongoDB is installed or not and run some mongo shell commands:
#!/bin/bash
if [ -f /usr/bin/mongod ]; then
echo "MongoDB is installed on your machine."
kill -0 "$$" || exit
else
password=password
echo "********************* MongoDB 4.0 INSTALL **************************"
echo "MongoDB is is not installed."
echo "******************************************************************"
echo $password | sudo apt-key adv --keyserver hkp://keyserver.ubuntu.com:80 --recv 68818C72E52529D4
echo $password | sudo bash -c "echo deb http://repo.mongodb.org/apt/ubuntu bionic/mongodb-org/4.0 multiverse" | sudo tee /etc/apt/sources.list.d/mongodb-org-4.0.list
sudo bash -c "apt update && apt upgrade -y"
sudo bash -c "apt-get install -y mongodb-org"
sudo bash -c "apt update && apt upgrade -y"
echo 'y' | sudo bash -c "apt autoremove && apt clean"
sudo bash -c "mkdir /data /data/db"
sudo bash -c "systemctl enable mongod" #enables Mongo on system startup
sudo bash -c "service mongod start"
sudo bash -c "service mongod restart"
kill -0 "$$" || exit
echo "********************* MongoDB Create DB and Collection **************************"
fi
mongod_status=`systemctl is-active mongod`
echo "${mongod_status}"
if [[ "${mongod_status}" == "active" ]]
then
echo "MongoDB is already running."
else
echo "MongoDB is not running"
rm /var/lib/mongodb/mongod.lock
sudo bash -c "service mongod start"
fi
mongo <<EOF
use fragment
db.createCollection("fragmenthash");
EOF
If my system is not installed with MongoDB, this script installs and start it. Then it checks the status, which is "active". But then when it executes mongo <<EOF section
, it returns
connecting to: mongodb://127.0.0.1:27017/?gssapiServiceName=mongodb
2021-05-19T10:06:01.134+0000 E QUERY [js] Error: couldn't connect to server 127.0.0.1:27017, connection attempt failed: SocketException: Error connecting to 127.0.0.1:27017 :: caused by :: Connection refused :
connect@src/mongo/shell/mongo.js:356:17
@(connect):2:6
exception: connect failed
Even if the status of MongoDB is Active still it gives this error. Whereas, if MongoDB is already installed, it executes the whole script successfully with creating DB and collection. Please help.