0

I have a javascript file ( .js ) that works on MongoDB. I run the .js file as mongo localhost:27017/dbname myjsfile.js .

How can I send command line arguments while running this JavaScript file ? I want to send database name and collection name as command line argument.

2 Answers 2

1

Well, you are already setting the database in use as you connect via:

mongo localhost:27017/dbname

So it is now on database "dbname". That is carried through to the db variable. Which is just a placeholder for the "current" database object.

That means that anything in your "script":

var results = db.collection.find().toArray();

For example is using the database you selected and the collection you named.

Need more? This is valid to:

db["mycollection"].find();

It's just JavaScript to the shell.

if you want a collection to be set as a variable then do something like this:

mongo localhost/mydb --eval "var users = db.users" myfile.js

Or otherwise just do that in you JavaScript file. You can test that by:

mongo localhost/mydb --eval "var users = db.users" --shell

And in the shell you now have a variable users that is "aliased" to the users collection.

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

5 Comments

ur reply is not clear to me. you didnt clearly tell how can I pass the collection name as an command line arument.
@prashantas There is some more information. Does that make things clear?
I know --eval will work but it is different from passing a shell variable
@wayne And unnecessary. Why parse JSON and not just load() JavaScript. Plus, the question asked "from the command line" And your answer says, "no you cannot". Hence the comment.
agree on unnecessary to load() javascript rather than parse. I feel parse give you an opportunity to catch an error. agree you answer the part can pass commandline but --eval is not necessary the solution for a number of usecase.
0

cli argument no. But you can read a json file and parse it in your script.

// config.json - {"dbname":"dbname","collection":"mycollection"}
var args = JSON.parse(cat("config.json"));

1 Comment

Not true. Anything you set in a JavaScript file that is loaded will be evaluated. You can even use load() for additional files. But of course you can use --eval on the command line as I have demonstrated. Have a look and a try yourself.

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.