Explore Courses Blog Tutorials Interview Questions
0 votes
in SQL by (47.6k points)

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


mongo myDbName 


show collections

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

How to execute other commands through shell script

2 Answers

0 votes
by (106k 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 (108k 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



Browse Categories