0 votes
1 view
in SQL by (47.8k points)

I want to execute mongo commands in the shell script, e.g. in a script test.sh:


mongo myDbName 


show collections

When I execute this script via ./test.sh, then the connection to MongoDB is established, but the following commands are not executed.

How to execute other commands through shell script test.sh?

2 Answers

0 votes
by (107k points)

To execute mongo commands through shell scripts you can also evaluate a command using the --eval flag if it is just a single command.

mongo --eval "printjson(db.serverStatus())"

0 votes
by (90.8k points)

Simply put your mongo script into a .js file and execute 

mongo < yourFile.js


demo.js //file has your script

use sample  //db name

show collections

Now keep this file in "c:db-scripts"

Then in cmd prompt go to "c:db-scripts"

C:db-scripts>mongo < demo.js

The above syntax will execute the code in mongo and shows the output as: 

C:db-scripts>mongo < demo.js

Mongo shell version: 3.0.4

Connecting to: test

switched to db sample

users   //collection name

tasks   //collection name



Welcome to Intellipaat Community. Get your technical queries answered by top developers !