Intellipaat Back

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

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

#!/bin/sh 

mongo myDbName 

db.mycollection.findOne() 

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?

3 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 (107k points)

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

mongo < yourFile.js

Example:

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

bye

C:db-scripts>

0 votes
ago by (1.8k points)

We can execute the commands of mongodb using shell scripts to do this we have to use mongo shell and there directly we can pass the commands
Step-1 Go to Mongo shell
Step-2 Hit command

mongo --eval "db.adminCommand('listDatabases')"

With the help of the above command we will be connected to mongodb server on port number 27017 and finally we can execute our specified command.

31k questions

32.8k answers

501 comments

693 users

Browse Categories

...