mongo shell脚本赢得';不要让我包括;使用<;数据库>&引用;

mongo shell脚本赢得';不要让我包括;使用<;数据库>&引用;,shell,mongodb,scripting,Shell,Mongodb,Scripting,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}); 通过输入以下2个shell命令对数据库dbTest运行: > use dbTest switched to dbTest > load("test.js") 到目前为止,一

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});
通过输入以下2个shell命令对数据库dbTest运行:

    > use dbTest
    switched to dbTest
    > load("test.js")
到目前为止,一切顺利

但如果我尝试在脚本中包含“use”语句,则会失败:

//script filename: test.js  (including "use" statement)
use dbTest;
db.cTest.save({Name: "Fred", Age:21});
失败,错误消息如下:

    > load("test.js")
    SyntaxError: missing ; before statement
    Mon Dec 19 11:56:31: Error: error loading js file temp.js (shell):1
在test.js中添加或删除分号似乎无关紧要

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

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

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

db2=connect(“服务器:27017/otherdbname”)


很遗憾,“load('file.js')”和“mongo file.js”实际上没有使用与交互式mongo shell相同的脚本解释器。在脚本中显式打开连接可能会违反DRY原则,因为mongo已经知道这些信息。不过,工作原理是将文件管道化到mongo中,而不是在命令行上传递其名称:

mongo <file.js

mongo在mongo脚本中,可以使用
db.getSiblingDB('new\u db\u name')
获取新数据库的引用。因此,在命令行中指定数据库名称不是强制性的。您可以使用
script.js

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

// the rest of your code for database "new_db_name"
MongoDB shell version: 2.2.2
connecting to: test
sag
该脚本的输出是(使用
mongo script.js
)调用):


谢谢超级有用当您想从mongo shell中编写快速脚本或函数时,这非常适合。切换数据库的关键行是db=db.getSiblingDB('new_db_name');下面的答案是正确的。要了解交互式JS和脚本JS之间的区别,请使用db_name;以前可以使用,现在在较新的版本中,我们必须使用上面提到的db名称进行连接