MongoDB’s aggregation pipeline lets you execute arbitrary JavaScript via $function, $accumulator, and $where (the latter on find). It is escape-hatch territory: useful when the built-in operators cannot express the transformation, dangerous when used to paper over schema problems. This article covers when server-side JavaScript is the right tool, the security knobs that control whether it runs at all, and the performance characteristics you accept when you reach for it.
How to verify
Check whether server-side JavaScript is enabled and try a small $function call:
mongosh --host primary.example.internal:27017
db.adminCommand({ getParameter: 1, javascriptEnabled: 1 })
use shop
db.orders.aggregate([
{ $project: {
sku: 1,
slug: { $function: {
body: "function(name) { return name.toLowerCase().replace(/\\s+/g, '-'); }",
args: ["$name"],
lang: "js"
} }
} },
{ $limit: 3 }
])
If javascriptEnabled is false (modern recommendation for hardened clusters), the $function call fails with an explicit error.
What’s happening
$function runs an arbitrary JS function as part of an aggregation stage. The function body, the input arguments, and the language (always “js”) are passed in the operator; the server compiles the function once per query and invokes it per document. $accumulator is the same idea for $group accumulators — you supply init, accumulate, merge, and optionally finalize JS functions.
The JavaScript engine is V8, isolated per query. Each invocation is a fresh JS environment; there is no shared state between document evaluations and no persistence between queries. Some MongoDB modules and globals (like BSON, ObjectId, Date) are available; arbitrary require, network access, and filesystem access are not.
The security model is binary: server-side JS is either enabled (default in some distributions, configurable) or disabled. When enabled, any user with query privileges on the database can execute arbitrary JS as the mongod process. This is why most production deployments disable it — security.javascriptEnabled: false in mongod.conf is a common hardening step. The cost: you lose $function, $accumulator, $where, mapReduce (deprecated but still around), and db.eval (removed since 4.2).
The procedure
-
Disable server-side JavaScript by default in production. Enable per-cluster only when a documented use case demands it.
security: javascriptEnabled: false -
Re-enable only when there is no aggregation-operator equivalent. Slugify, complex string parsing, custom hash functions are credible cases; most “I need JS” turns into “I should use
$reduceand$map”. -
Use
$functionfor per-document logic that cannot be expressed in built-in operators.db.products.aggregate([ { $set: { priceTaxed: { $function: { body: "function(price, region) { const rate = {QC: 0.14975, ON: 0.13, BC: 0.12}[region] || 0.05; return Math.round(price * (1 + rate) * 100) / 100; }", args: ["$price", "$shipRegion"], lang: "js" } } } } ]) -
Use
$accumulatorfor custom group reducers withinit/accumulate/merge/finalize.db.events.aggregate([ { $group: { _id: "$user", sessionStats: { $accumulator: { init: "function() { return { count: 0, totalMs: 0 }; }", accumulate: "function(state, dur) { return { count: state.count + 1, totalMs: state.totalMs + dur }; }", accumulateArgs: ["$duration"], merge: "function(a, b) { return { count: a.count + b.count, totalMs: a.totalMs + b.totalMs }; }", finalize: "function(state) { return state.totalMs / state.count; }", lang: "js" } } } } ]) -
Avoid
$whereinfindqueries. It cannot use indexes — every$wherequery is aCOLLSCANwith JS evaluation per document. Express the predicate as a regular MongoDB filter expression. -
Test JS functions out-of-database first. Errors inside
$functionproduce cryptic messages from inside the V8 engine; debug the function in Node first, then move it into the pipeline.
Operational notes
- JS is single-threaded per query. Each query’s
$functioninvocations are serialized on a single V8 context. Heavy JS becomes a single-CPU bottleneck regardless of cluster size. - JS evaluation is the slowest aggregation stage. A
$functionruns ~100× slower than the equivalent built-in operator. For a small projection on 1000 documents the difference is invisible; for a$groupover 10 M documents it is hours of wall clock. - Modules and external dependencies do not work. No npm, no
require('crypto'). The execution environment is sandboxed pure-JS only. $functiondoes not stream. The result of the function call is materialized in the document before passing to the next stage; large return values balloon pipeline memory.- Auditing JS is hard. A custom function in a stored aggregation pipeline is opaque to schema review. Prefer expressing transformations as data, not code.
Stack Harbor’s default position with clients is server-side JavaScript disabled; we enable it per-cluster only when the use case justifies it and the security implications are reviewed. When clients have inherited a deployment with heavy $function use, we work to replace it with built-in aggregation operators — both for performance and to allow re-enabling security hardening. See /en/services/managed-operations/ for the engagement model.