shell脚本 - 检查mongodb服务器是否正在运行

时间:2013-05-14 11:48:01

标签: mongodb shell

我有一个shell脚本来执行一些mongo db操作:

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

但是,如果mongod服务器没有运行,我得到:

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

mongo有没有办法检查连接状态?最终我想要这样的东西:

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

4 个答案:

答案 0 :(得分:19)

你应该能够像这样创建一个bash脚本:

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

答案 1 :(得分:3)

尝试在shell脚本中运行它: -

  

pgrep mongod

如果值为数字,则表示进程正在运行,如果获得空值,则将其标记为服务未运行...

答案 2 :(得分:1)

这是我跑来检查mongodb是否已启动:

# 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

答案 3 :(得分:0)

如果您具有管理权限,还可以执行sudo systemctl status mongod,该操作会为您提供许多有用的附加信息:

mongod.service - MongoDB Database Server
   Loaded: loaded (/lib/systemd/system/mongod.service; enabled; vendor preset: enabled)
   Active: active (running) since Thu 2019-03-14 09:26:53 UTC; 5 weeks 9 days ago
     Docs: https://docs.mongodb.org/manual
 Main PID: 420 (mongod)
   CGroup: /system.slice/mongod.service
           └─420 /usr/bin/mongod --config /etc/mongod.conf