user1452954
user1452954

Reputation: 89

Pass variable from command line to mongo command

I have a script which does:

mongo localhost:27017/MyDB --eval "db = connect("localhost:27017/SomeDB")"
mongo localhost:27017/MyDB --eval "db.copyDatabase(var1frombatch, var2frombatch)"
PAUSE

in which var1frombatch & var2frombatch are passed to this batch from c#.net code as %1, %2, my question is how can i use the variable in my --eval doe ?

I tried

mongo localhost:27017/MyDB --eval "db = connect("localhost:27017/SomeDB")"
mongo localhost:27017/MyDB --eval "db.copyDatabase('%1', '%2')"
PAUSE

but did not work

Upvotes: 0

Views: 1109

Answers (1)

Kevin
Kevin

Reputation: 516

MongoDB has an feature to run shell scripts on the command line. In your case, one javascript for multiple operations works better than evaluate multiple mongodb functions.

Run a script like:

%MONGODBDIR%mongo localhost:27017/SMSManagement --eval "var dbA = '%1', dbB = '%2'" %SCRIPTSDIR%\shellscript.js

And in your shellscript.js

print("Copying database from " + "database:" + dbA + " to " + "database:" + dbB);

var result = db.copyDatabase(dbA, dbB)
printjson(result);

The result will output like:

{ "ok" : 1 }

More information about this you can read here: https://docs.mongodb.com/manual/tutorial/write-scripts-for-the-mongo-shell/

Upvotes: 1

Related Questions