执行 js 文件时无法访问 MongoDB Shell 中的变量
我在 js 文件中编写了一个简单的函数,并想在 MongoDB 中执行它。我的代码如下所示:
var test = function() {
db.foo.insert({name:"huiboo"});
};
我的问题是,当我尝试执行类似脚本
./mongo server:27017/dbname test.js
并立即启动 MongoDB shell 时,我将无法访问 MongoDB Shell 中的变量“test”,并且无法执行功能。
但如果我这样做
./mongo server:27017/dbname --shell test.js
,那么我确实可以访问变量“test”,并且一切都会像预期的那样工作。但我不想在执行文件后启动 shell。我宁愿能够在已经运行的 MongoDB Shell 中执行变量“test”。
所以我的问题是:是否可以在不添加选项“--shell”的情况下访问 MongoDB Shell 中的变量?
注意:我使用 MongoDB 2.0.1
I wrote a simple function in a js-file and would like to execute it in MongoDB. My code looks like the following:
var test = function() {
db.foo.insert({name:"huiboo"});
};
My problem is that when I try to execute the script like
./mongo server:27017/dbname test.js
and start the MongoDB shell right after, then I won't have access to the variable "test" in the MongoDB Shell and can't execute the function.
But if I do it like this
./mongo server:27017/dbname --shell test.js
then I do have access to the variable "test" and everything works like it supposed to do. But I don't want to start the shell after executing the file. I rather would like to be able to execute the variable "test" in an already running MongoDB Shell.
So my question: Is it possible to have access to variables in the MongoDB Shell without adding the option "--shell"?
note: I use MongoDB 2.0.1
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(1)
不,mongo shell 的每个实例都有它自己的 JS 作用域。但是,您可以将 JS 函数存储在服务器端,这将允许您在任何 shell 实例中调用它:
有关详细信息: http://www.mongodb.org/display/DOCS/Server-side+Code+Execution#Server-sideCodeExecution-Storingfunctionsserverside
No, every instance of the mongo shell has it's own JS scope. You can however store the JS function server-side which will allow you to invoke it in any shell instance :
For details : http://www.mongodb.org/display/DOCS/Server-side+Code+Execution#Server-sideCodeExecution-Storingfunctionsserverside