4

how to run a Mongo db script on a remote server?

I know below command can be used for the same on local as mentioned here:How to execute mongo commands through shell scripts?

mongo < yourFile.js

I want to run this script on a remote server

mongodb:uri:mongodb://user:[email protected]:27017/mydb

3
  • 2
    Did you try connecting with the shell? What does this have to do with spring? Commented Jun 20, 2017 at 10:06
  • SSH there and do your job. Commented Jun 20, 2017 at 11:55
  • There is no direct use of spring to push this script.i will be using spring to fetch the contents later.Not tried with shell Commented Jun 20, 2017 at 11:59

3 Answers 3

9

With Mongo on local machine :

 mongo -u <user> -p <password> mongodb01d.mydomain.com:27017/mydb <yourFile.js>
Sign up to request clarification or add additional context in comments.

2 Comments

It works..Thanks! mongo -u user -p password mongodb01d.mydomain.com:27017/mydb < yourFile.js -changed for better file read from the path where 'yourFile.js' exist.
what about on remote server ?
2

It might be a little bit off topic, but in case you want to / have to use Powershell for a lack of options, you can run:

(Get-Content yourFile.js) | & mongo.exe 'mongodb://user:[email protected]:27017/mydb'

or

"print('Hello');print('Hello')" | & mongo.exe 'mongodb://user:[email protected]:27017/mydb'

or

& 'mongo.exe' 'mongodb://user:[email protected]:27017/mydb' --eval "print('Hello');print('Hello')"

I had some difficulties with $regex, because Powershell interpreted it as a variable, so I had to use `$regex (with an additional backtick) instead.

Comments

0

For standalone mongo setup (single node)

mongo -u <user> -p <password> mongodb://HOST_IP:27017/DB_NAME --eval 'MONGO_QUERY'

Example:

mongo mongodb://127.0.0.1:27017/test --eval 'db.collection.count()'

For clustered mongo setup (Replicaset with multiple nodes)

mongo -u <user> -p <password> mongodb://NODE_1_IP:27017,NODE_2_IP:27017,NODE_3_IP:27017/DB_NAME?replicaSet=RS_ID --eval 'MONGO_QUERY'

Example:

mongo mongodb://127.0.0.1:27017,127.0.0.2:27017,127.0.0.3:27017/test?replicaSet=rs0 --eval 'db.collection.count()'

PS: The user/pass in the above examples have been ignored but you need to add them if mongo has to auth.

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.