I am trying to run this command from 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 it without using a js file?
To open up the MongoDB shell, run the mongo command from your server prompt. By default, the mongo command opens a shell connected to a locally-installed MongoDB instance running on port 27017 . Try running the mongo command with no additional parameters: mongo.
Connect to MongoDB database You can start the server in CMD using the following command. Then type mongo command to run the shell. Now you are in the Mongo shell. If you want, you can run the mongo and mongod without the command prompt.
To start MongoDB, run mongod.exe from the Command Prompt navigate to your MongoDB Bin folder and run mongod command, it will start MongoDB main process and The waiting for connections message in the console.
You can use heredoc syntax.
#! /bin/sh
mongo <<EOF
use admin
db.shutdownServer()
quit()
exit
Turns out heredoc syntax throws a warning when EOF is missing at the end for bash script. This is the bash script version.
#! /bin/bash
mongo <<EOF
use admin
db.shutdownServer()
quit()
EOF
Here is the output, I guess this 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
There are differences between interactive & scripted mongo
shell sessions. In particular, commands like use admin
are not valid JavaScript and will only work in an interactive shell session.
The working equivalent of your shutdown command line would be:
mongo 192.168.10.20:27000/admin --eval "db.shutdownServer()"
You can include the database to use in the connection string, and there is no need to quit from a scripted mongo
shell session.
If you do need to change databases from a scripted session, there is a db.getSiblingDB()
JavaScript function. An alternative way to write the shutdown command above would be:
mongo 192.168.10.20:27000 --eval "db=db.getSiblingDB('admin');db.shutdownServer()"
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