Change mongosh to process and use arguments only up to a "--" sentinel
Getting command line arguments into mongosh is virtually impossible. The --eval option insists on printing the last eval expr evaluated to the console despite the --quiet switch. Allowing a script to self parse and manage any args following the "–" sentinel using the "process.argv" array would permit the developer a wide array of choices in handling script input from a command line.
" > mongosh mongo-options script file – arg arg... "
Component: mongosh
Versions: 1.4.x and up
-
Marshall commented
Massimillano;
That is more or less what I do now. It's a bit cumbersome since everything is wrapped in bash. I'm not sure how option 2 would work. I'll have to investigate and see how I could make that work.
Everything I'm doing currently has some kind of bash front end that calls some large JS script where parameters are supplied from the command line.
Regards
-
AdminMassimiliano (Admin, MongoDB) commented
There are a couple of ways to do that:
1. pass parameters with `eval` mongosh --eval 'parameter=value' yourscript.js, where the script can then read the parameters as variables
2. if at the end of your script you call exit(), whatever you put after that can be used as argument that you read in process.argv. -
Marshall commented
Wernfried:
I'm running with MongoDB 6.0 and mongosh 1.6.0 and this worked for me.
echo "db.getMongo();"|mongosh --quiet "mongodb://user:password@localhost/MHDB?authSource=admin"
MYDB> db.getMongo();
mongodb://<credentials>@localhost/MYDB?authSource=admin&directConnection=true&serverSelectionTimeoutMS=2000&appName=mongosh+1.6.0I can also get it to work as a "here" document. Example:
mongosh --quiet "mongodb://user:password@localhost/MHDB?authSource=admin" <<EOJS
use MYDB
db.getMongo()
EOJSMYDB> db.getMongo();
mongodb://<credentials>@localhost/MYDB?authSource=admin&directConnection=true&serverSelectionTimeoutMS=2000&appName=mongosh+1.6.0 -
Wernfried commented
In deed, in legacy mongo shell it was possible to pipe a command. In mongosh this does not work anymore:
Failing:
echo "db.getMongo()" | mongosh "mongodb://user:password@localhost/?authSource=admin"
db.getMongo()
{}Working:
echo "db.getMongo()" | mongo "mongodb://user:password@localhost/?authSource=admin"
connection to localhost:27017