- Reference >
- JavaScript Methods >
- db.eval()
db.eval()¶
-
db.
eval
(function, arguments)¶ The
db.eval()
provides the ability to run JavaScript code on the MongoDB server. It is amongo
shell wrapper around theeval
command. However, unlike theeval
command, thedb.eval()
method does not support thenolock
option.The method accepts the following parameters:
Parameters: - function (JavaScript) –
A JavaScript function.
The function need not take any arguments, as in the first example, or may optionally take arguments as in the second:
- arguments – A list of arguments to pass to the JavaScript
function
if the function accepts arguments. Omit if thefunction
does not take arguments.
Consider the following example of the
db.eval()
method:- The
db
in the function refers to the current database. "<name>"
is the argument passed to the function, and corresponds to thename
argument.5
is an argument to the function and corresponds to theincAmount
field.
If you want to use the server’s interpreter, you must run
db.eval()
. Otherwise, themongo
shell’s JavaScript interpreter evaluates functions entered directly into the shell.If an error occurs,
db.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,
db.eval()
takes a global write lock before evaluating the JavaScript function. As a result,db.eval()
blocks all other read and write operations to the database while thedb.eval()
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. db.eval()
also takes a JavaScript lock.- Do not use
db.eval()
for long running operations, asdb.eval()
blocks all other operations. Consider using other server side code execution options. - You can not use
db.eval()
with sharded data. In general, you should avoid usingdb.eval()
in sharded cluster; nevertheless, it is possible to usedb.eval()
with non-sharded collections and databases stored in sharded cluster. - With
authentication
enabled,db.eval()
will fail during the operation if you do not have the permission to perform a specified task.
See also
- function (JavaScript) –