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:

#!/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?

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 (82.1k 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>

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


Categories

...