How to execute mongo commands from bash?

I am trying to run this command from a bash script:

mongo 192.168.10.20:27000 --eval "use admin && db.shutdownServer() && quit()" 

but I get this error:

 [rs.initiate() && use admin && db.shutdownServer() && quit()] doesn't exist 

how can i do this without using js file?

+6
source share
3 answers

There are differences between interactive and scripted mongo shell mongo . In particular, commands like use admin not valid JavaScript and will only work in an interactive shell session.

The working equivalent of the shutdown command line is:

 mongo 192.168.10.20:27000/admin --eval "db.shutdownServer()" 

You can enable the database to be used in the connection string, and there is no need to exit the mongo shell mongo .

If you need to modify databases from a script, there is a JavaScript function db.getSiblingDB() . An alternative way to write the shutdown command above is:

  mongo 192.168.10.20:27000 --eval "db=db.getSiblingDB('admin');db.shutdownServer()" 
+13
source

You can use heredoc syntax.

 #! /bin/sh mongo <<EOF use admin db.shutdownServer() quit() exit 

Turns off the heredoc syntax, issues a warning when EOF is missing at the end for a bash script. This is the bash script version.

 #! /bin/bash mongo <<EOF use admin db.shutdownServer() quit() EOF 

Here is the result, I think, is what you expected.

 MongoDB shell version: 2.4.14 connecting to: test switched to db admin Wed Jun 24 17:07:23.808 DBClientCursor::init call() failed server should be down... Wed Jun 24 17:07:23.810 trying reconnect to 127.0.0.1:27017 Wed Jun 24 17:07:23.810 reconnect 127.0.0.1:27017 ok Wed Jun 24 17:07:23.812 Socket recv() errno:104 Connection reset by peer 127.0.0.1:27017 Wed Jun 24 17:07:23.812 SocketException: remote: 127.0.0.1:27017 error: 9001 socket exception [RECV_ERROR] server [127.0.0.1:27017] Wed Jun 24 17:07:23.812 DBClientCursor::init call() failed 
+9
source

From mongo docs :

- eval option

Use the -eval parameter for mongo to pass the JavaScript fragment to the shell, as shown below: mongo test --eval "printjson(db.getCollectionNames())"

You can also put your JS snippets in a .js file, and then do:

 mongo < myScript.js 

You can also find more useful stuff in this SO question.

+3
source

Source: https://habr.com/ru/post/989682/


All Articles