I have a bash script which fails. After inspection, it appears that the failure is due to the fact that MongoDB is accessed immediately after being restarted.
For example, running:
mongo --eval "db.version()"
gives the expected output:
MongoDB shell version: 2.4.9
connecting to: test
2.4.9
while running:
service mongodb restart; mongo --eval "db.version()"
produces the following output, emphasis mine:
mongodb stop/waiting
mongodb start/running, process 1466
MongoDB shell version: 2.4.9
connecting to: test
Sat Oct 25 02:52:29.736 Error: couldn't connect to server 127.0.0.1:27017 at src/mongo/shell/mongo.js:145
exception: connect failed
because the server is not ready yet.
What is the correct way to wait during the execution of the bash script until MongoDB is actually ready?
service mongodb status
is not a solution, because it reports the status of the service, and not the database itself.
Doing nc -z localhost 27017
repeatedly until its exit code becomes 0 will work, but I'm not sure if there are no drawbacks (running somehow an infinite loop?)
One liners to start or stop mongodb service using command line; To start the service use: NET START MONGODB. To stop the service use: NET STOP MONGODB.
To start the mongo interpreter without connection to any db:
mongo --nodb
From there, inside the mongo interpreter you can execute:
var conn;
try
{
conn = new Mongo("localhost:27017");
}
catch(Error)
{
//print(Error);
}
while(conn===undefined)
{
try
{
conn = new Mongo("localhost:27017");
}
catch(Error)
{
//print(Error);
}
sleep(100);
}
DB = conn.getDB("test");
Result = DB.runCommand('buildInfo');
print(Result.version);
With the 2 above, you can put the later part in a file like Script.js and then do:
mongo --nodb Script.js
EDIT: There, totally forgot that what you really wanted was the version. Fixed that for you.
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