- Reference >
- Database Commands >
- eval
eval¶
-
eval¶ The
evalcommand 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
functionif the function accepts arguments. Omit if thefunctiondoes not take arguments. - args (array) – An array of corresponding arguments to the
function. Omitargsif thefunctiondoes not take arguments. - nolock (boolean) –
Optional.
By default,
evaltakes a global write lock before evaluating the JavaScript function. As a result,evalblocks all other read and write operations to the database while theevaloperation runs. Setnolocktotrueon theevalcommand to prevent theevalcommand from taking the global write lock before evaluating the JavaScript.nolockdoes not impact whether operations within the JavaScript code itself takes a write lock.
Consider the following example which uses
evalto perform an increment and calculate the average on the server:The
dbin 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 thenolockoption.If you want to use the server’s interpreter, you must run
eval. Otherwise, themongoshell’s JavaScript interpreter evaluates functions entered directly into the shell.If an error occurs,
evalthrows an exception. Consider the following invalid function that uses the variablexwithout declaring it as an argument:The statement will result in the following exception:
Warning
- By default,
evaltakes a global write lock before evaluating the JavaScript function. As a result,evalblocks all other read and write operations to the database while theevaloperation runs. Setnolocktotrueon theevalcommand to prevent theevalcommand from taking the global write lock before evaluating the JavaScript.nolockdoes not impact whether operations within the JavaScript code itself takes a write lock. evalalso takes a JavaScript lock.- Do not use
evalfor long running operations asevalblocks all other operations. Consider using other server side code execution options. - You can not use
evalwith sharded data. In general, you should avoid usingevalin sharded cluster; nevertheless, it is possible to useevalwith non-sharded collections and databases stored in a sharded cluster. - With
authenticationenabled,evalwill fail during the operation if you do not have the permission to perform a specified task.
See also
- function (JavaScript) –