0

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

7
  • What does the parser execute? (run it with echo on to see) Commented May 27, 2016 at 6:27
  • nothing it cannot read %1 and %2 as batch variables Commented May 27, 2016 at 6:53
  • so your question isn't "how can I use the variable in the batchfile" but "how do I pass a variable to the batchfile". Sadly I can't help you with c#. Commented May 27, 2016 at 6:58
  • Thanks for the reply man, but that's not what i mean, i already have the variable passed into this batch script of mine. They are %1 and %2, now i want to use them in the --eval section as database names, but i cannot parse them Commented May 27, 2016 at 7:10
  • Why don't you solve this with PowerShell? Commented May 27, 2016 at 7:22

1 Answer 1

1

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/

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

3 Comments

hello thanks for your reply, your code did not work, the program cannot recognize %1 and %2 inside --eval
You told that %1 and %2 are the arguments? Place the script in a bat file and call batch.bat "DB_A" "DB_B"' and %1 and %2 should works like it supposed to.
Yeah, i tied and its working now, thanks a lot man, it was very helpful !

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.