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.

CategoryBSON Types
MongoDB Version1.0+
Example Languagemongosh (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

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.
Web-Tutorial.com

Web-Tutorial Tech Team

A team of developers maintaining programming tutorials. Each tutorial is written and reviewed by developers with expertise in that field. We work to keep our content accurate and reliable — if you spot an issue, please let us know.

100%

🙏 帮我们做得更好

我们是刚上线的编程教程站,几个人的小团队,精力有限。页面虽经检查,难免还有疏漏——链接失效、排版错乱、内容有误、语言生硬……

如果您发现了,麻烦告诉我们,我们会在收到反馈后第一时间进行修复,再次感谢您的光临 🙏