$where (JavaScript Expression)
Last updated: 2026-10-09
$where (JavaScript Expression)
$where evaluates a JavaScript expression as the query predicate. `{ $where: 'this.credits == this.debits' }`. It executes server-side, is slow, cannot use indexes, and MongoDB recommends $expr instead. Use it only when $expr cannot express the logic (e.g. custom JS functions) and guard against injection.
| Category | Element & Evaluation |
|---|---|
| MongoDB Version | 1.0+ |
| Example Language | mongosh (Shell) |
📝 Syntax
{ $where: <JavaScript expression> }
⚙️ Parameters
| JS expression | A JavaScript expression returning a boolean; this refers to the current document. |
|---|
Returns:Cursor of matching documents
▶ Example
Run the commands below in your local mongosh (requires a running mongod):
// $where: records where credits equal debits (JS)
db.accounts.find({ $where: 'this.credits == this.debits' })
// Recommended: $expr is faster
db.accounts.find({ $expr: { $eq: ['$credits', '$debits'] } })
Output:
// Both return the same result, but $expr performs better
📌 Notes
- Runs server-side JavaScript, cannot use indexes, poor performance
- Prefer $expr (MongoDB 3.6+)
- Injection risk: never concatenate user input into $where
🏷️ Related Tags
💡 Related Cases
More hands-on cases coming soon.
📚 Related Tutorials
❓ FAQ
QWhy is $where slow?
AIt evaluates JavaScript per document server-side with no index support.
QHow do I choose between $where and $expr?
APrefer $expr: better performance and index support; use $where only for custom JS logic.
QDoes $where have security risks?
AYes. Concatenating user input into the string enables injection; parameterize or switch to $expr.