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... "
Versions: 1.4.x and up
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.
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.
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"
I can also get it to work as a "here" document. Example:
mongosh --quiet "mongodb://user:password@localhost/MHDB?authSource=admin" <<EOJS
In deed, in legacy mongo shell it was possible to pipe a command. In mongosh this does not work anymore:
echo "db.getMongo()" | mongosh "mongodb://user:password@localhost/?authSource=admin"
echo "db.getMongo()" | mongo "mongodb://user:password@localhost/?authSource=admin"
connection to localhost:27017