How to pass argument to Mongo Script

Brig picture Brig · Apr 11, 2012 · Viewed 35.7k times · Source

I've been using mongo and script files like this:

$ mongo getSimilar.js

I would like to pass an argument to the file:

$ mongo getSimilar.js apples

And then in the script file pick up the argument passed in.

var arg  = $1;
print(arg);

Answer

jcollum picture jcollum · Apr 12, 2012

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