2

I've been working on some simple scripts to run on mongo from the bash command-line. Originally, I ran them as follows:

$ mongo dbname script.js

but I recently came across mikemaccana's answer, https://stackoverflow.com/a/23909051/2846766, indicating the use of mongo as an interpreter so I can just execute script.js (or any name I choose, with or without the .js) from the command line.

$ script.js

I think it's brilliant and clean, but now I'd like to pass in a database name as a command line argument.

$ script.js dbname

Here I use the bash-style "$1" to demonstrate what I'm doing in script.js.

#!/usr/bin/env mongo
var db = new Mongo().getDB($1);
// Do other things with db, once I resolve the name from the command line.

This results in a "ReferenceError: $1 is not defined ...", which is not surprising. But how would I reference command line arguments? Is this going to be a mongo convention? a javascript convention? Is it possible? It would make my command-line experience with mongo much better aesthetically.

Community
  • 1
  • 1
mightypile
  • 7,589
  • 3
  • 37
  • 42

3 Answers3

2

Currently there is no way to do this using the mongo shell...

https://groups.google.com/forum/#!topic/mongodb-user/-pO7Cec6Sjc

... try using a bash script (or other scripting language you are comfortable with) if you want to get a similar command line experience.

RScottCarson
  • 980
  • 5
  • 20
2

Duplicate of How to pass argument to Mongo Script In a nutshell, this is not possible but several workarounds are given in the answers (not repeated here).

Community
  • 1
  • 1
Florian
  • 874
  • 1
  • 8
  • 17
0

You can pass args to your script through

mongo --eval 'var databasePassword="password"' script.js

and you can access databasePassword value inside script.js

db.auth({ user: 'testUser, pwd: databasePassword });

Ron
  • 96
  • 2