Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Pass commands to Mongo shell from bash script without halting interactive Mongo shell

I am looking to create a bash script which connects to a remote Mongo database and initializes an interactive Mongo shell, issues a couple of commands to the interactive Mongo shell, and then enables the interactive shell to continue running so that I can continue entering commands into it.

Currently, I understand that I can connect to a Mongo database and issue a command to it within a bash script like so:

mongo <ip>:<port>/<database> --eval "db.auth('myuname', 'mypass');"

However, I would like my bash script to run the above command, and then keep the Mongo shell that was initialized running so that I can continue to use it and enter commands into it on my own. It seems that after running the above command, a Mongo shell is created and then halted immediately after the given db.auth() command is executed, but I would like to keep the shell running past this point.

like image 931
Tom Catullo Avatar asked Jan 30 '15 22:01

Tom Catullo


People also ask

What is the command to connect to the mongo shell?

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.

Is the interactive MongoDB shell?

MongoDB Mongo shell is an interactive JavaScript interface that allows you to interact with MongoDB instances through the command line. The shell can be used for: Data manipulation. Administrative operations such as maintenance of database instances.

What is the difference between mongo and Mongosh?

They are just different tools and hence different versions. mongosh is a recent introduction and mongo shell has been there for a while. Both these are command-line tools to access MongoDB server. Both have similar functionality.


1 Answers

Use the --shell option in addition to the --eval option. This will keep the mongo shell session open in interactive mode after the --eval code is run:

mongo --shell --eval "printjson('Hello, World!')"

You can also put commands in ~/.mongorc.js and /etc/mongorc.js that the shell will run when it is started by the current user or every time it is started, respectively. See the files section of the mongo shell docs.

like image 200
wdberkeley Avatar answered Oct 14 '22 17:10

wdberkeley