21

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.

4

2 回答 2

29
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
于 2011-07-19T20:02:27.840 回答
5

您可以使用这里MongoDB 文档db.getSiblingDB()中提到的方法。

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

use这在使用辅助程序不可用的 mongo shell 编写脚本时特别有用。或者当您无法在连接字符串上引用数据库时。

于 2020-11-04T14:30:49.793 回答