- Administration >
- Administration Tutorials >
- MongoDB Scripting >
- Server-side JavaScript
Server-side JavaScript¶
On this page
Overview¶
MongoDB provides the following commands, methods, and operator that perform server-side execution of JavaScript code:
mapReduce
and the correspondingmongo
shell methoddb.collection.mapReduce()
.mapReduce
operations map, or associate, values to keys, and for keys with multiple values, reduce the values for each key to a single object. For more information, see Map-Reduce.eval
command and the correspondingmongo
shell methoddb.eval()
.eval
operations evaluates JavaScript functions on the database server. You cannot use theeval
command anddb.eval()
method with sharded collections. For replica sets, you can only run theeval
command anddb.eval()
method against the primary. For more information, seeeval
command anddb.eval()
method reference pages.$where
operator that evaluates a JavaScript expression or a function in order to query for documents.
You can also specify a JavaScript file to the mongo
shell to
run on the server. For more information, see
Running .js files via a mongo shell Instance on the Server
JavaScript in MongoDB
Although the aforementioned operations use JavaScript, most interactions with MongoDB do not use JavaScript but use an idiomatic driver in the language of the interacting application.
You can also disable server-side execution of JavaScript. For details, see Disable Server-Side Execution of JavaScript.
Running .js
files via a mongo
shell Instance on the Server¶
You can specify a JavaScript (.js
) file to a mongo
shell
instance to execute the file on the server. This is a good technique
for performing batch administrative work. When you run mongo
shell on the server, connecting via the localhost interface, the
connection is fast with low latency.
The command helpers provided in the
mongo
shell are not available in JavaScript files because
they are not valid JavaScript. The following table maps the most common
mongo
shell helpers to their JavaScript equivalents.
Shell Helpers | JavaScript Equivalents |
---|---|
show dbs , show databases |
|
use <db> |
|
show collections |
|
show users |
|
show roles |
|
show log <logname> |
|
show logs |
|
it |
Concurrency¶
Changed in version 2.4.
The V8 JavaScript engine, which became the default in 2.4, allows
multiple JavaScript operations to execute at the same time. Prior to
2.4, MongoDB operations that required the JavaScript interpreter had to
acquire a lock, and a single mongod
could only run a single
JavaScript operation at a time.
Refer to the individual method or operator documentation for any concurrency information. See also the concurrency table.
Disable Server-Side Execution of JavaScript¶
You can disable all server-side execution of JavaScript, by passing the
--noscripting
option on the command
line or setting security.javascriptEnabled
in a
configuration file.