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.

3 Answers 3

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.

Sign up to request clarification or add additional context in comments.

Comments

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).

Comments

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 });

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.