Latest Update
Click here for more information on using the --eval option in MongoDB shell scripts.
Utilize the --eval option when running scripts in the mongo shell by passing a JavaScript fragment as shown below:
mongo test --eval "printjson(db.getCollectionNames())"
Method 1:
// script1.js
db.myCollection.insertOne({name: "New Company1", location: "Nice Location"})
// execute
mongo myDB script1.js
Method 2:
// script2.js
db.getSiblingDB('companies').myCollection.insertOne({name: "New Company", location: "Nice Location"});
db.getSiblingDB('companies1').myCollection.insertOne({name: "New Company", location: "Nice Location"});
db.getSiblingDB('companies3').myCollection.insertOne({name: "New Company", location: "Nice Location"})
// run
mongo script2.js
Yes, you can run the script somejavascriptfile.js
like this
mongo myDB somejavascriptfile.js // on a specific databse
mongo somejavascriptfile.js
Learn more about the --eval option in the MongoDB documentation.
--eval
Evaluates a JavaScript expression that is specified as an argument. mongo does not load its own environment when evaluating code. As a result, many options of the shell environment are not available.
mongo myDB --eval "var myVar = 'testVar'" somejavascriptfile.js // pass some variables to your script
Additionally, check out
This link provides information on how to load and run a JavaScript file in the MongoDB shell environment.
The load() method has the following parameter:
load("scripts/myjstest.js")
load("/data/db/scripts/myjstest.js")