Search code examples
mongodb

mongo shell - how to properly pass a parameter on a command line


I'm trying to do the following. I want to pass in an email address on the command line using --eval:

mongo --eval "var emailparam=foo.bar@yahoo.com" userfind.js

Where userfind.js:

use dev;
db.users.find({email:"emailparam"}).pretty();

Getting the following error:

$ mongo --eval "var emailparam=foo.bar@yahoo.com" userfind.js MongoDB shell version: 3.2.4 connecting to: test 2016-08-12T07:02:27.033-0700 E QUERY [thread1] SyntaxError: illegal character @(shell eval):1:25

**from the output above, I'm not also able to switch to my database dev using use dev.

I've tried escaping as well and no luck:

$ mongo --eval "var emailparam=foo.bar\@yahoo.com" userfind.js

Is there a way to do this?


Solution

  • Take a look at Write Scripts for the mongo shell. The first problem is that you can't do use dev; in your js file, you'd need to add this to your js file:

    db = db.getSiblingDB('dev')
    

    OR you can leave that out of your script and just pass the db name as a positional argument as part of your execution of the mongo shell:

    mongo dev --eval "var emailparam='foo.bar@yahoo.com'" userfind.js
    

    Also, you have emailparam in quotes in your js file, it should not be in quotes. When you call the mongo shell you need to have the variable value quoted which you'd need to escape using \" or use single quotes for the variable value.

    Last but not least, you need to iterate the cursor within your js file, the mongo shell does this for you automatically but you need to do this manually when executing via a script. (This is also described in the doc link provided above).

    userfind.js

    db = db.getSiblingDB('dev')
    cursor = db.users.find({email:emailparam});
    while ( cursor.hasNext() ) {
       printjson( cursor.next() );
    }
    

    And to call:

    mongo --eval "var emailparam='foo.bar@yahoo.com'" userfind.js