KeplerGrid guide

Index a MongoDB array field with a multikey index

Index a scalar field alongside an array field. Verify how MongoDB records the array path and check when a compound index can reject writes.

Load the practice collection

Run once in mongosh against a development instance with an empty products practice collection.

const lab = db.getSiblingDB("keplergrid_practice")
lab.products.insertMany([
  { _id: "notebook", workshop: "paper", tags: ["blue", "lined"] },
  { _id: "folder", workshop: "paper", tags: ["red"] },
  { _id: "cup", workshop: "ceramics", tags: ["blue"] }
])
lab.products.insertMany(Array.from({ length: 80 }, (_, i) => ({
  _id: "practice-" + i, workshop: "paper", tags: ["green"]
})))
lab.products.createIndex({ workshop: 1, tags: 1 }, { name: "workshop_tags" })

In KeplerGrid, open keplergrid_practice.products with a Read only connection.

Match one tag in KeplerGrid

Paste this into the Documents filter. Scalar equality on tags matches when the array contains that value.

{ "workshop": "paper", "tags": "blue" }

Only notebook matches. MongoDB makes the index multikey automatically because it indexes array values.

Confirm the index’s array path

In the same mongosh session, run the command below. Find indexName: "workshop_tags", isMultiKey: true, and the tags entry under multiKeyPaths.

lab.products.find({ workshop: "paper", tags: "blue" })
  .hint("workshop_tags").explain("executionStats")

The hint tests this index specifically. Check the unhinted plan to see what the optimizer chooses. A given document can have an array in at most one indexed field. A later insert or update can fail if it makes both workshop and tags arrays on the same document.

See how to match several conditions on the same array element or revisit the related KeplerGrid walkthrough.