Overview
MongoDB provides the following commands, methods, and operator that perform server-side execution of JavaScript code:
mapReduceand the correspondingmongoshell methoddb.collection.mapReduce(). For more information, see Map-Reduce.$whereoperator that evaluates a JavaScript expression or a function in order to query for documents.$accumulatorand$functionaggregation operations that allows users to define custom aggregation expressions.
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
Note
JavaScript in MongoDB
Although these methods use JavaScript, most interactions with MongoDB do not use JavaScript but use an idiomatic driver in the language of the interacting application.
If you do not need to perform server-side execution of JavaScript code, see Disable Server-Side Execution of JavaScript.
Note
If you are using SELinux, any MongoDB operation that requires server-side JavaScript will result in segfault errors. Disable Server-Side Execution of JavaScript describes how to disable execution of server-side 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.
Concurrency
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:
For a
mongodinstance by passing the--noscriptingoption on the command line or settingsecurity.javascriptEnabledto false in the configuration file.Starting in MongoDB 4.4, for a
mongosinstance by passing the--noscriptingoption on the command line or settingsecurity.javascriptEnabledto false in the configuration file.In earlier versions, MongoDB does not allow JavaScript execution onmongosinstances.