I want to execute mongo commands in shell script.
I tried following way test.sh
#!/bin/sh
mongo myDbName
db.mycollection.findOne()
show collections
When I execute above script ./test.sh
Then mongo connection established but next commands not executed
How to execute other commands through sh script [test.sh] ?
Please help me
Recently migrated from mongodb to Postgres. This is how I used the scripts.
Read the
scripts.js
and output redirect toinserts.sql
.scripts.js
looks like thisinserts.sql
looks like thisThis works for me under Linux:
Put this in a file called
test.js
:then run it with
mongo myDbName test.js
.The shell script below also worked nicely for me... definite had to use the redirect that Antonin mentioned at first... that gave me the idea to test the here document.
In case you have authentication enabled:
You can also evaluate a command using the
--eval
flag, if it is just a single command.Please note: if you are using Mongo operators, starting with a $ sign, you'll want to surround the eval argument in single quotes to keep the shell from evaluating the operator as an environment variable:
Otherwise you may see something like this: