24

I just want to run a .js script against a particular mongodb database, but can't seem to get the correct syntax.

echo "print(db.address.find().limit(1));" > test.js
mongo test.js

How do I select the database that this will be executed on, I've tried various combinations of use foo with no success.

> show dbs                      
admin   (empty)
local   (empty)
foo 0.203125GB
bar 0.203125GB

I would like to use foo in this case.

markdsievers
  • 7,151
  • 11
  • 51
  • 83

2 Answers2

31
mongo <name of db> --eval "db.runCommand( <js in here> );"

Or if you dont have a specific runCommand script, you can just do:

mongo <name of db> --eval "<js in here>;"

If you are using a return value:

mongo <name of db> --eval "db.eval('return fnName()')"

For a file

mongo <name of db> some_instructions.js
Chris Barretto
  • 9,379
  • 3
  • 42
  • 45
  • How can I specify a file? ie not put a lump of javascript in that command line function? – markdsievers Jul 19 '11 at 20:05
  • 1
    Remember that double quotes in bash will treat `$` (and [some other characters](https://stackoverflow.com/questions/6697753/difference-between-single-and-double-quotes-in-bash)) as special characters! So you should either use single quotes (`''`) or escape `$` and other special characters with a backslash: `mongo mydbname --eval "JSON.stringify( db.mycollectionname.find({count: {\$lte:1} }).limit(2).toArray() )"` It may be worth changing the quotes in your answer to single quotes, Chris? –  Jul 05 '17 at 02:18
9

You can use the db.getSiblingDB() method, as mentioned here and in the MongoDB documentation.

// Equivalent for "use <db>" command in mongo shell
db = db.getSiblingDB('foo')

This is particularly useful when writing scripts using the mongo shell where the use helper is not available. Or when you cannot refer to the DB on the connection string.

idrositis
  • 1,136
  • 10
  • 10