- Reference >
- Database Commands >
- eval
eval¶
-
eval
¶ The
eval
command evaluates JavaScript functions on the database server and has the following form:The command contains the following fields:
Fields: - function (JavaScript) –
A JavaScript function.
The function may accept no arguments, as in the following example:
The function can also accept arguments, as in the following example:
- arguments – A list of arguments to pass to the JavaScript
function
if the function accepts arguments. Omit if thefunction
does not take arguments. - args (array) – An array of corresponding arguments to the
function
. Omitargs
if thefunction
does not take arguments. - nolock (boolean) –
Optional.
By default,
eval
takes a global write lock before evaluating the JavaScript function. As a result,eval
blocks all other read and write operations to the database while theeval
operation runs. Setnolock
totrue
on theeval
command to prevent theeval
command from taking the global write lock before evaluating the JavaScript.nolock
does not impact whether operations within the JavaScript code itself takes a write lock.
Consider the following example which uses
eval
to perform an increment and calculate the average on the server:The
db
in the function refers to the current database.The shell also provides a helper method
db.eval()
, so you can express the above as follows:The
db.eval()
method does not support thenolock
option.If you want to use the server’s interpreter, you must run
eval
. Otherwise, themongo
shell’s JavaScript interpreter evaluates functions entered directly into the shell.If an error occurs,
eval
throws an exception. Consider the following invalid function that uses the variablex
without declaring it as an argument:The statement will result in the following exception:
Warning
- By default,
eval
takes a global write lock before evaluating the JavaScript function. As a result,eval
blocks all other read and write operations to the database while theeval
operation runs. Setnolock
totrue
on theeval
command to prevent theeval
command from taking the global write lock before evaluating the JavaScript.nolock
does not impact whether operations within the JavaScript code itself takes a write lock. eval
also takes a JavaScript lock.- Do not use
eval
for long running operations aseval
blocks all other operations. Consider using other server side code execution options. - You can not use
eval
with sharded data. In general, you should avoid usingeval
in sharded cluster; nevertheless, it is possible to useeval
with non-sharded collections and databases stored in a sharded cluster. - With
authentication
enabled,eval
will fail during the operation if you do not have the permission to perform a specified task.
See also
- function (JavaScript) –