Skip to content
Tutorials Center
My learning

Topics

Lesson 61 of 70 ยท Security

NoSQL Injection and Safe Queries

Understand NoSQL injection in MongoDB: how $ne and $gt in a JSON body bypass a login, why $where is risky, and how to validate, coerce and sanitize input safely.

Everyone has heard of SQL injection: untrusted text gets glued into a query string and changes what the query means. MongoDB does not parse a query string, so that exact attack does not work. Queries are documents, and drivers send them as structured data. It is tempting to conclude that MongoDB is immune, and that conclusion is wrong. The attack moves up a level: if an attacker can control the shape of the document you pass as a filter, they can swap a plain value for an operator such as { "$ne": null } and change the meaning of the query. This is called operator injection, one form of NoSQL injection.

This lesson shows the bug, then the fixes. The examples run on a small stand-in matcher written in plain JavaScript, so you can see the attack succeed and then fail. The stand-in is not MongoDB, but the filter documents and the vulnerability are exactly the real ones. Server-side JavaScript topics ($where) are shown as read-only code. Background on operators is in Comparison Operators, and the Node.js side in Using MongoDB from Node.js.

Only run attacks like these against systems you own. The goal here is to recognise and prevent the bug in your own code.

How operator injection works

JSON in The request body becomes the filter.
Shape changes A string is replaced by an object.
Meaning changes $ne null matches every password.

The bug is trusting the type of user input.

1 / 2

The vulnerable login

Imagine a Node.js login route that reads a JSON body and looks the user up directly:

JavaScript
app.post("/login", async (req, res) => {
  const user = await db.collection("users").findOne({
    email: req.body.email,
    password: req.body.password,        // (also wrong: passwords must be hashed)
  });
  if (user) res.json({ ok: true });
  else res.status(401).json({ ok: false });
});

A normal client sends {"email": "[email protected]", "password": "hunter2"}, and the filter is an equality check on two strings. But nothing forces the password to be a string. An attacker can send:

JSON
{ "email": "[email protected]", "password": { "$ne": null } }

Express's JSON parser happily produces a real object, so the filter becomes { email: "[email protected]", password: { $ne: null } }, which reads "email matches and the password is not null". Every user with any password matches, and the attacker is logged in without knowing it. The same trick works with { "$gt": "" }, and with { "$regex": "^a" } it can even be used to guess a stored value one character at a time. (Storing passwords in plain text, as in this simplified route, is a separate serious mistake: real systems store only a salted hash and verify it in application code, which also removes this particular query.)

Form-encoded bodies are affected too: parsers such as qs turn password[$ne]=x into a nested object. The underlying problem is the same everywhere: input from the outside arrived with a type you did not expect, and you passed it straight into a filter.

The first stand-in reproduces this with a small matcher that supports equality, $ne and $gt. Watch the attack succeed against the vulnerable route.

JS Operator injection against a vulnerable login

Press Run (or Ctrl + Enter) to see the console output here.

No output.

The last line is worse than the one before it: with $gt: "" on both fields, the attacker does not even need to know any email address, and the first user in the collection is returned.

Fix 1: check the type

The simplest defence is to insist that values you expect to be strings really are strings, and reject anything else before the query is built.

JavaScript
if (typeof req.body.email !== "string" || typeof req.body.password !== "string") {
  return res.status(400).json({ error: "invalid input" });
}

You can also coerce instead of reject: String(value) turns an object into the harmless text "[object Object]", which then simply fails to match. Rejection is clearer and gives better error handling, but both close the hole. The rule to remember is that every field of user input that reaches a filter must have a known, checked type: strings, numbers, booleans, or an ObjectId built from a validated string. Never pass req.body, req.query or any parsed object directly as a filter or as an update document.

Fix 2: remove operator keys

When a feature genuinely accepts structured input (for example a search form with several optional filters), you can strip or refuse any key that starts with $ or contains a dot, recursively. Libraries exist for this, such as express-mongo-sanitize, but it is worth seeing the idea in a few lines. Sanitising is a safety net, though, not a substitute for validating types and building the filter yourself from named fields.

Fix 3: validate the shape at the edge

The most robust approach is to declare what each endpoint accepts and build the filter from validated fields only. A validation library (Zod, Joi, Ajv for JSON Schema) does that declaratively; the stand-in below does the same by hand so you can see the pieces working together: reject non-strings, strip operator keys, and build the query from a whitelist of fields.

JS Three defences against the same attack

Press Run (or Ctrl + Enter) to see the console output here.

No output.

In defence 2 notice what happens to the attack: the password key survives only if it was a plain value, so after stripping, password becomes an empty object {}, which the matcher treats as a non-match. Stripping alone therefore blocked the login here, but you would not want to rely on it for fields where an empty object might mean something. Type checks and whitelisting are the stronger tools, and defences are best layered.

$where and server-side JavaScript

MongoDB can run JavaScript on the server in a few places: the $where query operator, $function and $accumulator in aggregation (and older mechanisms such as mapReduce). A $where clause takes a string or function and evaluates it for each document:

JavaScript
// Dangerous: user text becomes code that runs inside the database
db.users.find({ $where: "this.name == '" + req.query.name + "'" })
// name = "x'; return true; var a='"   makes the condition true for every document

This is a real injection of code, closer to classic SQL injection, and the code runs inside the database process. Server-side JavaScript is also slow, because it cannot use indexes and runs per document, and it can be turned off completely with security.javascriptEnabled: false in the server configuration (check the documentation for your version). The best advice is to avoid it: nearly everything $where can do is available through normal operators, $expr, or the aggregation framework (Expressions and Operators).

Other safe-query habits

  • Hash passwords in the application with a password hashing function (bcrypt, scrypt, Argon2) and compare in code. Do not query by password at all: look the user up by email, then verify the hash.
  • Limit what the filter can reach. Search endpoints should accept named parameters, not a whole filter object from the client.
  • Be careful with $regex built from input. A user-supplied pattern can match too much or be expensive; escape special characters when you mean literal text (Text Matching and Regular Expressions).
  • Use least privilege. If the application account cannot drop collections or read other databases (Authentication and Role-Based Access), a successful injection does less damage.
  • Parse ids deliberately. Convert strings to ObjectId with a validity check rather than passing arbitrary objects as _id.
  • Do not leak details. Return a generic "invalid credentials" message, not the raw database error.

Check your understanding

Quick check ยท 4 questions

of 4 answered You scored / 4 ยท perfect!

  1. 1. A login route builds the filter { email: body.email, password: body.password } from JSON. Which request body bypasses the password check?

    The password value is an object holding the operator $ne, so the filter means 'password is not null', which matches any stored password.
  2. 2. What is the most direct fix for operator injection in a login route?

    The attack depends on a non-string value reaching the filter. Enforcing the expected types removes that.
  3. 3. Why is $where with user input considered risky?

    $where evaluates a JavaScript expression on the server. Concatenating user text into it lets an attacker alter the logic or run unwanted code, and it cannot use indexes.
  4. 4. Which approach is generally the strongest way to build a search filter from request data?

    Whitelisting and validating named fields means the client can never introduce operators or unexpected keys, no matter what it sends.

Summary

  • MongoDB has no query string to inject into, but passing untrusted objects as filters allows operator injection ($ne, $gt, $regex).
  • The classic example is a login bypass with { "password": { "$ne": null } }.
  • Fix it by validating types, stripping $ and dotted keys, and building filters from a whitelist of named fields; layer these defences.
  • $where and other server-side JavaScript can turn input into code: avoid them or disable server-side JavaScript.
  • Hash passwords and verify in application code; use least privilege and generic error messages.

Now put the pieces together in a small data layer in Project: A Task Tracker Data Layer.