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