Security Concepts9 min read11 October 2026

What Is NoSQL Injection? MongoDB, Redis and Beyond | Yrzo AI

NoSQL injection exploits how document and key-value databases process untrusted input. Learn how attacks work against MongoDB, Redis, and Cassandra, and how to prevent them.

By Yrzo AI — UK cybersecurity specialists

What Is NoSQL Injection?

NoSQL injection is an attack that exploits the way non-relational databases interpret user-supplied data. While SQL injection is well understood and widely discussed, NoSQL injection is less visible in mainstream security training — despite affecting a vast number of modern web applications built on MongoDB, Redis, CouchDB, Cassandra, Firebase, and similar databases.

The core dynamic is the same as SQL injection: unsanitised user input reaches the database layer in a form the database interprets as control logic rather than data. The mechanics differ by database, and the impact ranges from authentication bypass to complete data exfiltration to remote code execution.

MongoDB Operator Injection

MongoDB stores documents in a JSON-like format and queries them using operators: `$eq`, `$gt`, `$lt`, `$ne`, `$in`, `$regex`, and many others. If user input reaches a MongoDB query without sanitisation, an attacker can inject these operators to alter the query's logic.

Authentication Bypass

Consider a login endpoint that takes a JSON body:

```javascript // Vulnerable Node.js + MongoDB authentication const user = await db.collection("users").findOne({ email: req.body.email, password: req.body.password }); ```

The intended query is: ```json { "email": "user@example.com", "password": "correctpassword" } ```

An attacker sends: ```json { "email": "admin@example.com", "password": { "$ne": "anything" } } ```

MongoDB interprets `$ne` as "not equal to". The query now finds a user whose password is not equal to "anything" — which is every user. Authentication is bypassed. The attacker logs in as the target account without knowing the password.

The same attack works with `$gt`, `$regex`, and other comparison operators depending on the field type.

Data Exfiltration via $regex

The `$regex` operator enables blind data exfiltration. An attacker can probe field values character by character:

```json { "username": "admin", "password": { "$regex": "^a" } } { "username": "admin", "password": { "$regex": "^ab" } } { "username": "admin", "password": { "$regex": "^abc" } } ```

Each request tests whether the password starts with a given prefix. A match (successful login) confirms the prefix. Iterating through the character space recovers the full password value — effective against stored plain-text or weakly hashed passwords.

Parameter Pollution via URL Encoding

When MongoDB queries are built from URL query parameters, the same injection is possible via parameter pollution. Many web frameworks (Express.js with the qs library, for example) parse `?password[$ne]=x` as `{ password: { $ne: "x" } }` automatically — turning a URL parameter into a MongoDB operator without the developer explicitly allowing it.

``` GET /api/users?email=admin@example.com&password[$ne]=anything ```

The framework parses the bracket notation and the operator injection occurs transparently.

**Remediation for MongoDB:** ```javascript import { sanitize } from "express-mongo-sanitize";

// Strip $ and . from keys in req.body, req.query, req.params app.use(sanitize());

// Or manually validate input types function loginQuery(email, password) { if (typeof email !== "string" || typeof password !== "string") { throw new Error("Invalid input types"); } return db.collection("users").findOne({ email, password }); } ```

Redis Injection

Redis is a key-value store used as a cache, message broker, and session store in high-traffic applications. It uses a text-based protocol where commands are separated by newlines. If user input is embedded in Redis commands without sanitisation, an attacker can inject additional commands.

Command Injection

A vulnerable session lookup:

```python # Vulnerable — constructs Redis command with unsanitised user input session_key = f"session:{user_provided_session_id}" redis_command = f"GET {session_key}" result = redis.execute_command(redis_command) ```

Attacker input: `abc\r\nSET admin_key hacked\r\n`

The injected `\r\n` sequences are CRLF characters — the Redis protocol separator. The server executes: ``` GET session:abc SET admin_key hacked ```

The attacker has injected an arbitrary Redis command. Depending on the Redis configuration, this can be escalated to file writes using the `CONFIG SET dir` and `SLAVEOF` commands, potentially leading to remote code execution.

**Remediation for Redis:**

Use client libraries that handle command serialisation properly — never construct raw Redis commands via string concatenation. The `ioredis` and `redis` Node.js clients, Python's `redis` library, and similar properly serialise arguments:

```javascript // Safe — ioredis handles serialisation const session = await redis.get(`session:${sessionId}`); ```

Apply Redis authentication (`requirepass`) and network binding (`bind 127.0.0.1`) to limit exposure even if injection is present.

CouchDB and Mango Query Injection

CouchDB's Mango query language uses JSON selectors similar to MongoDB. The same operator injection patterns apply:

```json { "selector": { "email": "admin@example.com", "password": { "$gt": "" } } } ```

CouchDB also exposes a web interface (Fauxton) and an HTTP API. Injection in the query selector can extract all documents if the attacker controls the selector structure.

Firebase / Firestore Security Rules Bypass

Firestore uses client-side security rules to control data access. These rules run on Google's servers, but they can be bypassed when:

- Rules contain logic errors that permit unintended access - Client-side code constructs queries with unsanitised user input that meets rule conditions unintentionally - Rules are overly permissive (the default for new Firestore databases is fully open)

The impact of a Firestore rules bypass is direct access to the database from any authenticated (or unauthenticated) client.

Detection and Testing

Penetration testers probe NoSQL injection by:

1. **Input type testing** — Sending objects, arrays, and operator-keyed JSON where strings are expected 2. **URL parameter pollution** — Testing bracket notation in query strings (`field[$ne]=x`) 3. **Boolean-based blind testing** — Sending conditions that should match vs conditions that should not, comparing responses 4. **Regex-based blind exfiltration** — Using `$regex` with progressively longer prefixes to recover field values 5. **Error-based testing** — Sending malformed operators to trigger error messages revealing database structure

Automated scanners test these patterns systematically across every input parameter and JSON body field in the application.

General Remediation Principles

**Validate input types** — Before passing any value to a database query, verify it is the expected type. A password field expecting a string should reject objects, arrays, and any value that is not a string.

**Use safe query construction** — Use your database library's parameterised query methods or query builder. Never concatenate user input into query strings or command strings.

**Use a sanitisation library** — For MongoDB, `express-mongo-sanitize` removes operator keys from request objects. For Redis, use client libraries that serialise commands properly.

**Apply least privilege** — The database user account used by the application should have only the permissions it needs. A MongoDB user with read-only access to a specific collection cannot be used to exfiltrate other collections even if injection is possible.

**Enable authentication and network binding** — NoSQL databases are frequently deployed with no authentication and bound to all interfaces. A Redis or MongoDB instance accessible from the internet with no authentication turns injection into direct access.

How Yrzo AI Detects NoSQL Injection

Yrzo AI's scanner submits a range of NoSQL injection payloads — operator objects, parameter pollution via bracket notation, regex probes — to every input field, JSON body parameter, and URL query parameter it identifies. Detection uses both error-based indicators and response differential analysis to confirm injection without requiring verbose error messages. Confirmed findings include the injected payload, the response evidence, and the fix.

[Scan your application at yrzoai.dev](https://yrzoai.dev) — results within 24 hours, no installation required.

Find out if your website has these vulnerabilities

Yrzo AI runs 44 automated security checks and delivers a full report in under 20 minutes. Starting from £399.

Scan your website →