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.
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.
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.
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.
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.
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