JavaScript (Server-Side Code)
Last updated: 2026-10-09
JavaScript (Server-Side Code)
The JavaScript type stores JS code in a document, executed server-side through `$where` (run per document). `$where` cannot use indexes and is slow — fit only for small collections or logic no query operator can express. Since MongoDB 8.0, server-side JavaScript is disabled by default and needs an explicit startup flag; prefer `$expr` or the `$function` aggregation operator in new code.
| Category | BSON Types |
|---|---|
| MongoDB Version | 1.0+ |
| Example Language | mongosh (Shell) |
📝 Syntax
{ $where: "this.price * this.qty > 100" }
{ $expr: { $gt: [{ $multiply: ["$price", "$qty"] }, 100] } }
Returns:$where returns documents passing the predicate; stored JS values are code strings
▶ Example
Run the commands below in your local mongosh (requires a running mongod):
// JavaScript: server-side $where
use shop
db.orders.find({ $where: 'this.price * this.qty > 1000' })
Output:
// Orders where price * qty > 1000 (collection scan)
📌 Notes
- $where runs JS per document, can't use indexes, and is slow
- Server-side JS is off by default since 8.0 (enable via --enableJavaScriptExecution)
- Prefer $expr/$function for safer, faster equivalents
🏷️ Related Tags
💡 Related Cases
More hands-on cases coming soon.
📚 Related Tutorials
❓ FAQ
QWhy is $where slow?
AIt invokes a JS interpreter per document, cannot use indexes, and forces a full scan.
QDoes $where still work in MongoDB 8.0?
ADisabled by default; start the server with --enableJavaScriptExecution to turn it back on.
QHow do I express complex cross-field comparisons?
AUse $expr with aggregation operators like $multiply — optimizable and partially index-friendly.