3

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:password@mongodb01d.mydomain.com:27017/mydb

shabinjo
  • 1,473
  • 1
  • 16
  • 22

3 Answers3

9

With Mongo on local machine :

 mongo -u <user> -p <password> mongodb01d.mydomain.com:27017/mydb <yourFile.js>
DamienzOnly
  • 88
  • 1
  • 10
tronic
  • 459
  • 2
  • 11
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:password@mongodb01d.mydomain.com:27017/mydb'

or

"print('Hello');print('Hello')" | & mongo.exe 'mongodb://user:password@mongodb01d.mydomain.com:27017/mydb'

or

& 'mongo.exe' 'mongodb://user:password@mongodb01d.mydomain.com: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.

B--rian
  • 5,578
  • 10
  • 38
  • 89
0815 163
  • 51
  • 3
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.

Ashraf Sarhan
  • 1,507
  • 16
  • 21