【问题标题】:mongo shell script won't let me include "use <database>"mongo shell 脚本不允许我包含“使用 <database>”
【发布时间】:2012-01-23 19:43:45
【问题描述】:

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 脚本中呢?

【问题讨论】:

    标签: shell mongodb scripting


    【解决方案1】:

    在 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"
    

    这个脚本的输出是(用mongo script.js调用):

    MongoDB shell version: 2.2.2
    connecting to: test
    sag
    

    【讨论】:

    • 谢谢!超级有用
    • 当您想在 mongo shell 中编写快速脚本或函数时,这非常适合。切换数据库的关键是 db = db.getSiblingDB('new_db_name');
    • 文档可以在here找到
    【解决方案2】:

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

    mongo <file.js
    

    【讨论】:

    【解决方案3】:

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

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

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

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

    【讨论】:

    • 下面的答案是正确的。有关交互式 JS 和脚本化 JS 之间区别的概述:docs.mongodb.com/manual/tutorial/…
    • 使用 db_name;以前可以工作,现在在较新的版本中,我们必须如上所述连接数据库名称。
    猜你喜欢
    • 2014-03-03
    • 1970-01-01
    • 1970-01-01
    • 2016-04-09
    • 2014-08-16
    • 1970-01-01
    • 2014-07-21
    • 2015-09-14
    相关资源
    最近更新 更多