mongo shell 脚本不允许我包含“use”
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 脚本中呢?
32-bit mongo 2.0.1 on a windows XP machine
//script filename: test.js (one line shell script file to store a person)
db.cTest.save({Name: "Fred", Age:21});
run against database dbTest by entering the following 2 shell commands:
> use dbTest
switched to dbTest
> load("test.js")
So far, so good.
But if I try and include the "use" statement in the script it fails:
//script filename: test.js (including "use" statement)
use dbTest;
db.cTest.save({Name: "Fred", Age:21});
fails with error msg as follows:
> load("test.js")
SyntaxError: missing ; before statement
Mon Dec 19 11:56:31: Error: error loading js file temp.js (shell):1
Adding or removing semicolons to test.js doesn't seem to matter.
So how do you put a "use" directive into a mongo shell script?
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(3)
在 mongo 脚本中,您可以使用 db.getSiblingDB('new_db_name') 来获取新数据库的引用。因此,不必在命令行中给出数据库名称。您可以使用
script.js
:该脚本的输出为(使用
mongo script.js
调用):In a mongo script you can use the
db.getSiblingDB('new_db_name')
to get a reference of a new database. So, it it not mandatory to give the database name in the command line. You can use thescript.js
:and the output of this script is (invoked with
mongo script.js
):http://www.mongodb.org/display/DOCS/Scripting+the+shell
http://www.mongodb.org/display/DOCS/Scripting+the+shell
好吧,不幸的是“load('file.js')”和“mongo file.js”实际上并没有使用与交互式 mongo shell 相同的脚本解释器。在脚本中显式打开连接可能违反 DRY 原则,因为 mongo 已经知道该信息。不过,有效的方法是将文件通过管道传输到 mongo 中,而不是在命令行上传递其名称:
Well, it still is unfortunate that "load('file.js')" and "mongo file.js" don't actually use the same script interpreter as the interactive mongo shell. Opening the connection explicitly in the script is potentially a violation of the DRY principle because mongo already knows that information. What does work, though, is piping the file into mongo rather than passing its name on the command line: