Course contentsShow
← Security
Lesson 595 of 3,05213. Web Security - Injection AttacksFree lesson

MongoDB Injection Techniques

Exploiting operator injection in MongoDB queries using $where, $ne, $gt and JavaScript execution for authentication bypass.

MongoDB Injection Techniques

What you'll learn: How attackers exploit MongoDB's operator-based queries to bypass authentication and manipulate data—even when traditional SQL injection won't work.

Why MongoDB Injection Differs

MongoDB uses JSON-like documents and JavaScript-based queries instead of SQL. While this eliminates classic SQL injection, it introduces operator injection. Attackers inject MongoDB operators (special keys starting with $) or JavaScript code into queries that expect simple string values.

Think of it like this: if SQL injection is tricking a gatekeeper by changing the question they ask, MongoDB injection is smuggling in special instructions disguised as normal answers.

Key Operators Used in Attacks

$ne (not equal): Bypassing authentication by making comparisons always true:

// Intended query: {username: "admin", password: "userInput"}
// Attack payload: {"$ne": null}
// Result: {username: "admin", password: {"$ne": null}} → matches any password!

$gt (greater than): Similar bypass by comparing against empty strings:

{username: {"$gt": ""}, password: {"$gt": ""}} // Matches first user found

$where (JavaScript execution): Injecting code directly into query logic:

// Attack: {username: "admin", password: {"$where": "1==1"}}
// Executes arbitrary JavaScript in the database context

Authentication Bypass Example

When a login form passes user input directly to MongoDB without sanitization, an attacker can submit JSON operators instead of plain text. The query evaluates the operator logic rather than checking an exact password match—instantly granting access.

Key Takeaway: MongoDB injection exploits operator syntax ($ne, $gt, $where) to transform intended exact-match queries into always-true conditions, enabling authentication bypass and data extraction without SQL syntax.