Last updated: May 1, 2026
Why this module exists. Developers who learned about SQL injection often think NoSQL databases are safe by design. They aren’t — they have different injection patterns, often with even fewer guardrails. MongoDB powers half of Indian Node.js startups; nearly every one I’ve audited had at least one NoSQLi exposure.
How NoSQL queries differ from SQL
SQL: server interprets a string of SQL syntax. NoSQL: server executes a structured object — usually JSON or BSON.
MongoDB query (Node.js):
db.users.findOne({ username: req.body.username, password: req.body.password })
If req.body is { "username": "alice", "password": "secret" } → safe lookup.
If req.body is { "username": "alice", "password": { "$ne": null } } → query becomes { username: "alice", password: { $ne: null } } → matches alice with any non-null password → authentication bypass.
The two main injection classes
Operator injection — the attacker injects MongoDB operators ($ne, $gt, $regex, $where) by sending JSON instead of strings.
JavaScript injection — MongoDB’s $where operator executes JavaScript on the server. Inject JS, get RCE on the database server.
Common entry points in 2026
- Login forms accepting JSON bodies that pass user input into
findOne. - Search APIs that accept arbitrary filter expressions (“flexibility” features).
- GraphQL resolvers that pass user-supplied filter objects to MongoDB drivers.
- Express routes that destructure
req.queryorreq.bodydirectly into queries. - JSON Schema validators that allow extra properties.
Authentication bypass — the canonical example
Vulnerable Express endpoint:
app.post("/login", async (req, res) => {
const { username, password } = req.body;
const user = await db.users.findOne({ username, password });
if (user) return res.json({ token: signToken(user) });
return res.status(401).end();
});
Attack:
POST /login
Content-Type: application/json
{ "username": "admin", "password": { "$ne": null } }
If a user named “admin” exists with any non-null password, the query returns the admin record. Token issued to attacker.
Even worse — the attacker doesn’t need to know the username:
{ "username": { "$gt": "" }, "password": { "$gt": "" } }
Returns the first user in the collection (often an admin in dev/test data that survived to production).
Blind boolean extraction with $regex
If the response only differs (login OK / login fail), use $regex to extract data character by character:
{ "username": "admin", "password": { "$regex": "^a" } } # password starts with 'a'?
{ "username": "admin", "password": { "$regex": "^a.*" } } # 200 = yes
# Iterate: ^aa, ^ab, ^ac... discover password char by char
Slow but reliable. Automatable with NoSQLMap.
JavaScript RCE via $where
If the application allows $where (rare in modern code, common in legacy):
{ "$where": "function() { return this.username == 'admin' \u0026\u0026 sleep(5000); }" }
The MongoDB server executes the JS. With sleep, you’ve confirmed code execution. Move on to building proper RCE — though MongoDB’s JS sandbox is limited (no require, no shell access in modern versions).
Real-world cases
- Rocket.Chat 2020 — NoSQL injection in password reset → admin takeover.
- Strapi CVE-2023-22894 — NoSQL injection in template-literal parsing → admin auth bypass.
- Many bug-bounty disclosures on HackerOne targeting MongoDB-backed apps; “MongoDB-backed authentication bypass” is a common report category.
Try this yourself
# Damn Vulnerable NoSQL Application (DVNA)
git clone https://github.com/appsecco/dvna && cd dvna
docker compose up
# Or quick MongoDB lab
docker run --rm -p 27017:27017 mongo
mongosh
> use testdb
> db.users.insertOne({ username: "admin", password: "supersecret" })
# Vulnerable Express app
cat > app.js << 'EOF'
const express = require("express");
const { MongoClient } = require("mongodb");
const app = express();
app.use(express.json());
const c = new MongoClient("mongodb://localhost:27017");
app.post("/login", async (req, res) => {
await c.connect();
const u = await c.db("testdb").collection("users").findOne(req.body);
res.json(u ? { ok: true, user: u } : { ok: false });
});
app.listen(3000);
EOF
node app.js &
# Attack
curl -X POST -H "Content-Type: application/json" \
-d '{"username":"admin","password":{"$ne":null}}' \
http://localhost:3000/login
Defender’s checklist
- Type validation — every field expected to be a string must be validated as a string.
typeof password !== "string"→ reject. Express middleware:express-mongo-sanitize,mongo-sanitize. - JSON Schema validation — Zod, Joi, AJV — enforce that login bodies are exactly
{ username: string, password: string }. - Disable $where globally — MongoDB connection option
--noscriptingblocks server-side JS execution. Most apps don’t need it. - Parameterise queries — never spread
req.bodyinto a query. Pick fields explicitly. - SAST — Semgrep rule for “object spread into Mongo find” patterns.
- Detection — log queries containing
$ne,$gt,$regex,$wherefrom request paths that should never need them.
Module Quiz · 6 questions
Pass with 80%+ to mark this module complete. Unlimited retries. Each question shows an explanation.
Practical depth on what to tune, what to harden, and how this maps to Indian regulatory expectations.
NoSQL injection — different syntax, same root cause
NoSQL databases (MongoDB, CouchDB, Cassandra, Elasticsearch) avoid SQL but reintroduce injection in different forms.
MongoDB operator injectionquery {username: user_input, password: pass_input} with user_input = {"$ne": null} matches any user. JavaScript injection via $where: server-side eval allows arbitrary JS.
Aggregation pipeline injectionpipelines built from string concatenation.
Elasticsearch script injectionPainless scripts compiled from user input.
Defencesparameterise queries (every modern driver supports object-form queries with bind variables); reject input containing $ at the validation layer; prefer query-builder libraries over string concatenation; disable server-side script eval where possible.
Operational + India context
--noscripting); index every queried field for performance.NoSQL DoS — patterns beyond injection
NoSQL stores are vulnerable to denial-of-service patterns that SQL DBs have hardened against.
--maxTimeMS).Elasticsearch / Solr — the often-forgotten search store
Elasticsearch and Solr are NoSQL stores that frequently end up exposed. Common findings:
MongoDB authentication and access-control patterns
Production MongoDB hardening:
--auth mandatory; default unauthenticated mode is for dev only.Performance discipline that strengthens security
A practical performance discipline that applies regardless of the specific vulnerability class is to instrument every endpoint with three SLOs: latency at the 50th, 95th, and 99th percentiles. The 50th percentile reflects typical user experience, the 95th catches tail behaviour visible to a meaningful fraction of users, and the 99th captures the long-tail outliers that often hide bugs (timeouts on a stale dependency, locking contention under load, garbage-collection pauses on a hot endpoint). Every release should compare these percentiles against the previous baseline; regressions of more than ten percent on the 95th percentile are typically worth investigating before shipping. Modern observability stacks make this routine — Datadog APM, New Relic, Honeycomb, Grafana Tempo with OpenTelemetry instrumentation, and on the open-source side Jaeger plus Prometheus plus Grafana — but the discipline matters more than the tool. Indian product teams that have adopted this percentile-driven culture report fewer surprise outages and a smaller incident-response load over time, which compounds into a stronger security posture: the same instrumentation that catches a slow endpoint also catches an exploitation attempt that forces unusual code paths.
Observability that catches attacks alongside outages
Observability for security overlaps with observability for reliability but adds a few specific signals worth instrumenting. First, application-layer authentication and authorisation events should produce structured logs with the user identifier, the action attempted, the source IP, the User-Agent fingerprint, and the outcome. Second, every state-changing API call should log its idempotency key, the request body shape, and the resulting object identifier. Third, every external dependency call should log the destination, the response code, and the latency. Together these three categories produce a clean event stream that a SIEM can correlate to detect both functional regressions and active attacks. The cost is moderate — log storage in Elasticsearch or Splunk runs perhaps thirty to sixty rupees per gigabyte per year at typical Indian-tier prices — and the payoff is dramatic: incidents that previously took days to investigate are typically resolved in hours when the relevant evidence has been pre-indexed. Indian regulators increasingly expect this level of operational logging, particularly RBI under the Cyber Security Framework Annex 1 and SEBI under the CSCRF master circular.
DPDP and sectoral obligations a practitioner cannot ignore
Under India’s Digital Personal Data Protection Act 2023, the operational obligations on any web application that handles personal data extend beyond simple consent collection. Section 8 requires that data fiduciaries implement reasonable security safeguards — interpreted in practice as reflecting a documented information security programme, regular vulnerability assessment, and demonstrable controls aligned to a recognised standard such as ISO 27001 or NIST CSF. Section 9 imposes data principal rights including access, correction, and erasure, which means the application must be architected so that these requests can be fulfilled within the prescribed timeframes (currently expected to be on the order of thirty days). Section 8(6) imposes breach notification: when a personal-data breach occurs, the data fiduciary must notify the Data Protection Board and affected data principals within prescribed timeframes (the draft Rules suggest seventy-two hours for material breaches). For the practitioner this translates into specific engineering tasks: data inventory and lineage tracking, retention controls and automated deletion at end-of-purpose, audit-grade logging of every access to personal data, breach-detection telemetry, and a formal incident-response playbook with regulatory-notification templates. The 2024-2025 inspections by RBI and SEBI of regulated entities have already cited DPDP-overlay obligations, so the alignment is not theoretical; it shapes what auditors expect to see in the next inspection cycle.
A small threat-modelling routine before every release
A short threat-modelling exercise specific to this vulnerability class is worth running before each release. The classic STRIDE framework — Spoofing, Tampering, Repudiation, Information disclosure, Denial of service, Elevation of privilege — provides a useful checklist when applied to the specific data flow at hand. Begin by drawing the data flow for the feature being changed: external actors at the edge, the trust boundaries they cross, the back-end services involved, the data stores read or written, and the third-party integrations called. For each trust boundary crossing, ask which STRIDE categories apply and what controls mitigate them. The output is a small set of testable assertions: this endpoint must not allow tenant A to read tenant B’s records, this mutation must require step-up authentication, this third-party call must validate the response signature, and so on. Convert each assertion into an automated test or a manual verification step in the release checklist. The discipline pays off in two ways: first, it catches design-level bugs before they reach code review; second, it produces an auditable record of security thinking that regulators value. Indian product teams that have institutionalised this practice report fewer security incidents and shorter mean-time-to-remediate when issues are found, which compounds into better customer trust and lower regulatory friction over time.
Further reading
Additional FAQs
Are query-builder libraries safe?
Generally yes — they bind parameters as data. The escape hatches (db.eval, raw-string queries) are the danger. Audit every use of these.
Should I run MongoDB exposed to the internet?
No, ever. MongoDB sees more exposed-and-pillaged instances than any other database. VPN or VPC-only access; authentication enabled; TLS in transit.
Custom team training + practitioner advisory
Beyond the free academy — we run private workshops, vCISO advisory, and red-team exercises tailored to your stack. For Indian SMBs scaling past their first hire.