How To Pass Argument To Mongo Script
I've been using mongo and script files like this: $ mongo getSimilar.js I would like to pass an argument to the file: $ mongo getSimilar.js apples And then in the script file pic
Solution 1:
Use --eval
and use shell scripting to modify the command passed in.
mongo --eval "print('apples');"
Or make global variables (credit to Tad Marshall):
$ cat addthem.js
printjson( param1 + param2 );
$ ./mongo --nodb --quiet --eval"var param1=7, param2=8" addthem.js
15
Solution 2:
You can't do that, but you could put them in another script and load that first:
// vars.js
msg = "apples";
and getSimilar.js was:
print(msg);
Then:
$mongovars.jsgetSimilar.jsMongoDB shell version:blahconnecting to:testloading file:vars.jsloading file:getSimilar.jsapples
Not quite as convenient, though.
Solution 3:
Set a shell var:
password='bladiebla'
Create js script:
cat <<EOT > mongo-create-user.js
print('drop user admin');
db.dropUser('admin');
db.createUser({
user: 'admin',
pwd: '${password}',
roles: [ 'readWrite']
});
EOT
Pass script to mongo:
mongo mongo-create-user.js
Solution 4:
I used a shell script to pipe a mongo command to mongo. In the mongo command I used an arg I passed to the shell script (i.e. i used $1
):
#!/bin/sh
objId=$1
EVAL="db.account.find({\"_id\" : \"$objId\"})"echo$EVAL | mongo localhost:27718/balance_mgmt --quiet
Solution 5:
I wrote a small utility to solve the problem for myself. With the mongoexec
utility, you would be able to run the command ./getSimilar.js apples
by adding the following to the beginning of your script:
#!/usr/bin/mongoexec --quiet
Within the script, you can then access the arguments as args[0]
.
Post a Comment for "How To Pass Argument To Mongo Script"