How to pass argument to Mongo Script

Solution 1:

Use --eval and use shell scripting to modify the command passed in.

mongo --eval "print('apples');"

Or make global variables (credit to Tad Marshall):

$ cat addthem.js
printjson( param1 + param2 );
$ ./mongo --nodb --quiet --eval "var param1=7, param2=8" addthem.js
15

Solution 2:

You can't do that, but you could put them in another script and load that first:

// vars.js
msg = "apples";

and getSimilar.js was:

print(msg);

Then:

$ mongo vars.js getSimilar.js
MongoDB shell version: blah
connecting to: test
loading file: vars.js
loading file: getSimilar.js
apples

Not quite as convenient, though.

Solution 3:

Set a shell var:

password='bladiebla'

Create js script:

cat <<EOT > mongo-create-user.js
print('drop user admin');
db.dropUser('admin');
db.createUser({
user: 'admin',
pwd: '${password}',
roles: [ 'readWrite']
});
EOT

Pass script to mongo:

mongo mongo-create-user.js