mongo shell脚本不会让我包含"use <database>"

tpa*_*ale 31 shell scripting mongodb

Windows XP机器上的32位mongo 2.0.1

//script filename: test.js  (one line shell script file to store a person)
db.cTest.save({Name: "Fred", Age:21});
Run Code Online (Sandbox Code Playgroud)

通过输入以下2个shell命令对数据库dbTest运行:

    > use dbTest
    switched to dbTest
    > load("test.js")
Run Code Online (Sandbox Code Playgroud)

到现在为止还挺好.

但是,如果我尝试在脚本中包含"use"语句,它将失败:

//script filename: test.js  (including "use" statement)
use dbTest;
db.cTest.save({Name: "Fred", Age:21});
Run Code Online (Sandbox Code Playgroud)

失败,错误消息如下:

    > load("test.js")
    SyntaxError: missing ; before statement
    Mon Dec 19 11:56:31: Error: error loading js file temp.js (shell):1
Run Code Online (Sandbox Code Playgroud)

添加或删除分号到test.js似乎并不重要.

那么如何将"use"指令放入mongo shell脚本中呢?

Gab*_*vay 56

在mongo脚本中,您可以使用它db.getSiblingDB('new_db_name')来获取新数据库的引用.因此,不必在命令行中提供数据库名称.你可以使用script.js:

db = db.getSiblingDB('new_db_name');
print(db);

// the rest of your code for database "new_db_name"
Run Code Online (Sandbox Code Playgroud)

并且(使用mongo script.js)调用此脚本的输出:

MongoDB shell version: 2.2.2
connecting to: test
sag
Run Code Online (Sandbox Code Playgroud)


hel*_*nic 19

http://www.mongodb.org/display/DOCS/Scripting+the+shell

使用dbname
此命令在脚本模式下不起作用.相反,您需要在连接中显式定义数据库(上例中的/ dbname).

或者,您也可以在脚本中创建连接:

db2 = connect("server:27017/otherdbname")


Ola*_*hat 16

好吧,仍然不幸的是"load('file.js')"和"mongo file.js"实际上并没有使用与交互式mongo shell相同的脚本解释器.在脚本中显式打开连接可能违反了DRY原则,因为mongo已经知道该信息.但是,工作是将文件传递到mongo而不是在命令行上传递它的名称:

mongo <file.js
Run Code Online (Sandbox Code Playgroud)