Skip to content

Comments

fix(mongodb): skip $$REMOVE check for required fields to enable index usage#5724

Open
Kkartik14 wants to merge 1 commit intoprisma:mainfrom
Kkartik14:fix/mongodb-index-bypass
Open

fix(mongodb): skip $$REMOVE check for required fields to enable index usage#5724
Kkartik14 wants to merge 1 commit intoprisma:mainfrom
Kkartik14:fix/mongodb-index-bypass

Conversation

@Kkartik14
Copy link

Description

Fixes prisma/prisma#29000

This PR fixes a critical performance issue where all MongoDB queries bypass indexes due to unconditional $$REMOVE checks.

Problem

Previously, every scalar filter in mongodb-query-connector was wrapped with:

{ $and: [<filter>, { $ne: ["$field", "$$REMOVE"] }] }

This forces MongoDB to use $expr (aggregation expressions), which cannot use indexes, causing full collection scans (COLLSCAN) on every query—including _id and @unique field lookups.

Root Cause

The exclude_undefineds() function was designed to handle optional fields that might be undefined in MongoDB documents. However, it was being called unconditionally for all fields, including:

  • _id primary key (impossible to be missing)
  • @unique required fields (have indexes that should be used)
  • Required fields (Prisma enforces on create, cannot be missing)

Solution

Only add the $$REMOVE check for optional fields. Required fields and _id cannot be undefined by definition.

Added !field.is_required() condition before calling exclude_undefineds() in:

  • default_scalar_filter() (line 278)
  • insensitive_scalar_filter() (line 421)

Related Issues

@CLAassistant
Copy link

CLAassistant commented Jan 11, 2026

CLA assistant check
All committers have signed the CLA.

@Kkartik14 Kkartik14 changed the title fix(mongodb): skip 40139REMOVE check for required fields to enable index usage fix(mongodb): skip $REMOVE check for required fields to enable index usage Jan 11, 2026
@Kkartik14 Kkartik14 changed the title fix(mongodb): skip $REMOVE check for required fields to enable index usage fix(mongodb): skip $$REMOVE check for required fields to enable index usage Jan 11, 2026
@codspeed-hq
Copy link

codspeed-hq bot commented Jan 13, 2026

CodSpeed Performance Report

Merging this PR will not alter performance

Comparing Kkartik14:fix/mongodb-index-bypass (e9f3bea) with main (56fb1a4)

Summary

✅ 11 untouched benchmarks
⏩ 11 skipped benchmarks1

Footnotes

  1. 11 benchmarks were skipped, so the baseline results were used instead. If they were deleted from the codebase, click here and archive them to remove them from the performance reports.

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Labels

None yet

Projects

None yet

Development

Successfully merging this pull request may close these issues.

[MongoDB] All queries use $expr + $$REMOVE, bypassing indexes even for _id, @unique, and required fields

2 participants