8

I am trying to connect to a remote MongoDB instance using a shell script, but I am not able to connect.

  #!/bin/sh

mongo --eval "db = connect('sm-repository2.db.qa.test.com:27017/testdb')"

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

This tries to connect to my local mongo instance and gives me this error :

Error: couldn't connect to server 127.0.0.1 shell/mongo.js:84`
3
  • Could be an escape sequence issue? Can you try mongo --eval "db = connect('sm-repository2.db.qa.test.com:27017/testdb')"? Commented Mar 13, 2014 at 1:23
  • Thanks for pointing that out. But that doesn't help. Commented Mar 13, 2014 at 1:28
  • May be it's because you are opening 2 separate mongo shells? Can you try passing all javascript code in one mongo shell command? If not can you add log statements to confirm which line is exactly failing? Commented Mar 13, 2014 at 1:50

1 Answer 1

10

What you want is:

 mongo sm-repository2.db.qa.test.com:27017/testdb --eval "db.stats()"

Or for longer scripts:

 mongo sm-repository2.db.qa.test.com:27017/testdb script.js

See the full options in the documentation.

Sign up to request clarification or add additional context in comments.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.