I want to pass the environment variable named file_path
to js file.
I am using the following syntax:
mongo --eval \"var file_path=\'$fil
Looks like Native Method shellGetEnv()
has been added meanwhile, see MongoDB GitHub
So, would be simple
shellGetEnv("file_path")
However, the method is not documented and it looks it is not accessible from Mongo shell. Perhaps it becomes available in future releases.
There's a suggestion from the mongo change request:
alias mongo="export | sed 's/declare -x /env./' > shell.js; mongo $@; rm shell.js;"
Then in ~/mongorc.js
:
var env = {};
load('shell.js');
Since Mongo 4.0.5
it is possible to utilize some of the new admin functions to load text files and execute programs.
So you can write a Javascript function to execute a shell script that provides the value of an environment variable:
function getEnvValue(envVar, defVal) {
var ret= run("sh", "-c", `printenv ${envVar} >/tmp/${envVar}.txt`);
if (ret != 0) return defVal;
return cat(`/tmp/${envVar}.txt`)
}
And then using it like this:
db.createCollection("myCol",
{ capped: true,
size: getEnvValue('MYCOL_MAX_SIZE_GB', 2)*1024*1024*1024
});
This relies on the host shell but was acceptable in my case (Docker).
Was also trying to read the environ
directly:
cat('/proc/self/environ').split('\0') # Doesn't work
but it only gets the first variable. I guess because of the null characters...
This worked for me:
mongo --eval "var my_var = '$MY_VAR'" my_script.js
Leave out the <
. mongo
will process any remaining arguments on the command line as files to be executed/interpreted, but apparently combining the shell input redirect with --eval
causes the javascript namespace to be reset.
I assume but cannot confirm that this is because filenames passed as arguments are processed via the load()
mechanism, which according to https://docs.mongodb.com/v3.2/reference/method/load/, behaves as follows:
After executing a file with load(), you may reference any functions or variables defined the file from the mongo shell environment.