How to pass an argument to Mongo Script

I use mongo and script files as follows:

$ mongo getSimilar.js 

I would like to pass an argument to the file:

 $ mongo getSimilar.js apples 

And then in the script file, select the argument passed.

 var arg = $1; print(arg); 
+47
javascript scripting mongodb
Apr 11 2018-12-12T00:
source share
5 answers

Use --eval and use shell scripts to modify the passed command.

mongo --eval "print('apples');"

Or make global variables (credit Tad Marshall):

 $ cat addthem.js printjson( param1 + param2 ); $ ./mongo --nodb --quiet --eval "var param1=7, param2=8" addthem.js 15 
+83
Apr 11 2018-12-12T00:
source share

You cannot do this, but you can put them in another script and load first:

 // vars.js msg = "apples"; 

and getSimilar.js:

 print(msg); 

Then:

 $ mongo vars.js getSimilar.js MongoDB shell version: blah connecting to: test loading file: vars.js loading file: getSimilar.js apples 

Not very convenient.

+14
Apr 11 2018-12-12T00:
source share

I used the shell script to connect the mongo command to mongo. In the mongo command, I used arg, which 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 
+2
Feb 24 '16 at 20:01
source share

Define the var shell:

 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 
+1
Mar 09 '15 at 11:19
source share

I wrote a small utility to solve the problem for myself. Using the mongoexec utility mongoexec you can run the ./getSimilar.js apples command, adding the following to the top of your script:

 #!/usr/bin/mongoexec --quiet 

Inside the script, you can access arguments like args[0] .

https://github.com/pveierland/mongoexec

0
Jun 13 '17 at 22:26
source share



All Articles