KeplerGrid guide

Compare MongoDB regex index plans with Explain

Compare three name searches against one ascending index. A case-sensitive literal prefix can give MongoDB a smaller key range. Use Explain to see how much of the index each search actually examines.

Index 1,200 synthetic depot names

Run this once in mongosh on a disposable MongoDB instance. Use a fresh collection with the default simple collation and an account allowed to insert and create an index there.

const lab = db.getSiblingDB("keplergrid_regex_lab")
lab.depots.insertMany(Array.from({ length: 1200 }, (_, i) => ({
  _id: i + 1,
  name: (i < 12 ? "North-" : i < 24 ? "north-" :
    i < 36 ? "Depot North-" : "Depot-") + String(i).padStart(4, "0")
})))
lab.depots.createIndex({ name: 1 })

Connect KeplerGrid in Read only mode, open keplergrid_regex_lab.depots, and confirm name_1 appears in Indexes.

Explain a case-sensitive prefix

Open Aggregation → JSON, paste this pipeline, and select Explain. The caret anchors the search at the start of the field.

[
  { "$match": { "name": { "$regex": "^North-" } } }
]

On the practice data, the winning plan uses name_1 and returns 12 documents. Find Keys examined and Documents examined in the summary. The key count describes how much of the index MongoDB read for this plan.

KeplerGrid Explain for the anchored prefix shows name_1, thirteen keys examined, and twelve documents returned
In the practice collection the anchored, case-sensitive prefix examined 13 index keys and returned 12 matching documents.

Compare ignoring case and matching anywhere

Run Explain for each pipeline separately. The first also matches the lowercase prefix. The second matches the uppercase text anywhere in the field.

[
  { "$match": { "name": { "$regex": "^North-", "$options": "i" } } }
]
[
  { "$match": { "name": { "$regex": "North-" } } }
]

All three winning plans used the name_1 index with an IXSCAN stage on MongoDB 8.0.20.

Execution statistics on the practice collection
PatternReturnedKeys examinedDocuments examined
^North-121312
^North- with i24120024
North-24120024

Both alternatives return 24 documents, but they include different names. The case-insensitive search includes north-0012. The unanchored search includes Depot North-0024. Select Run pipeline to check that the results answer the intended question.

Keep the match semantics your application needs. Compare the measured plans on representative data, since MongoDB can choose a different plan with different data or indexes.

See more MongoDB text filters or learn to read an Explain plan.

Next, Search MongoDB documents with a text index and $text.