Databases Reference
In-Depth Information
> db.eval("function(u) { print('Hello, '+u+'!'); }", [username])
You can pass in as many arguments as necessary. For instance, if we want a sum of
three numbers, we can do the following:
> db.eval("function(x,y,z) { return x + y + z; }", [num1, num2, num3])
num1
becomes
x
,
num2
becomes
y
, and
num3
becomes
z
. If you would like to use a variable
number of parameters, arguments in JavaScript are stored in an
arguments
array when
a function is called.
As a
db.eval
expression becomes more complex, debugging can be tricky. The Java-
Script code is run by the database and often doesn't have useful line numbers in error
messages. A good way of debugging is printing to the database log, which you can do
with the print function:
> db.eval("print('Hello, world');");
Stored JavaScript
MongoDB has a special collection for each database called
system.js
, which can store
JavaScript variables. These variables can then be used in any of MongoDB's JavaScript
contexts, including
"$where"
clauses,
db.eval
calls, and MapReduce jobs. You can add
variables to
system.js
with a simple insert:
> db.system.js.insert({"_id" : "x", "value" : 1})
> db.system.js.insert({"_id" : "y", "value" : 2})
> db.system.js.insert({"_id" : "z", "value" : 3})
This defines variables
x
,
y
, and
z
in the global scope. Now, if we want to find their sum,
we can execute the following:
> db.eval("return x+y+z;")
6
system.js
can be used to store JavaScript code as well as simple values. This can be
handy for defining your own utilities. For example, if you want to create a logging
function to use in JavaScript code, you can store it in
system.js
:
> db.system.js.insert({"_id" : "log", "value" :
... function(msg, level) {
... var levels = ["DEBUG", "WARN", "ERROR", "FATAL"];
... level = level ? level : 0; // check if level is defined
... var now = new Date();
... print(now + " " + levels[level] + msg);
... }})
Now, in any JavaScript context, you can call this log function:
> db.eval("x = 1; log('x is '+x); x = 2; log('x is greater than 1', 1);");
The database log will then contain something like this:
Fri Jun 11 2010 11:12:39 GMT-0400 (EST) DEBUG x is 1
Fri Jun 11 2010 11:12:40 GMT-0400 (EST) WARN x is greater than 1