prashantas
prashantas

Reputation: 455

command line argument to a javascript file that works on mongodb

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.

Upvotes: 0

Views: 1439

Answers (2)

Neil Lunn
Neil Lunn

Reputation: 151072

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.

Upvotes: 1

wayne
wayne

Reputation: 3410

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

Upvotes: 0

Related Questions