KeplerGrid guide

Enforce per-tenant uniqueness with a MongoDB compound index

Allow the same external ID in two tenants while preventing duplicates within one tenant. Check the combination before building the index.

Load the practice collection

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

const lab = db.getSiblingDB("keplergrid_practice")
lab.tenantItems.insertMany([
  { _id: "north-1", tenant: "north", externalId: "SKU-7" },
  { _id: "south-1", tenant: "south", externalId: "SKU-7" },
  { _id: "north-2", tenant: "north", externalId: "SKU-8" }
])

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

Check for duplicate pairs

In Aggregation → JSON, run a group by the same two scalar fields that the index will use. This practice collection gives every row both fields.

[
  { "$group": { "_id": { "tenant": "$tenant", "externalId": "$externalId" },
                "documents": { "$sum": 1 } } },
  { "$match": { "documents": { "$gt": 1 } } }
]

Expect zero results. SKU-7 occurs twice, but each occurrence belongs to a different tenant. For real data, check missing, null, and array values and confirm the desired index collation before using a duplicate scan.

Build the two-field unique index

Run this on the disposable collection in the same shell. Then open Indexes in KeplerGrid and confirm the key order and index name.

lab.tenantItems.createIndex(
  { tenant: 1, externalId: 1 },
  { unique: true, name: "tenant_external_unique" }
)

A concurrent conflicting write can still cause an index build to fail after the scan. Existing single-field indexes remain separate rules.

Verify the constraint with a conflicting insert

Attempt a second SKU-7 for the north tenant. The different _id makes this a test of the compound rule.

lab.tenantItems.insertOne({ _id: "north-conflict", tenant: "north", externalId: "SKU-7" })

Expect a duplicate key error and no new north record. The original south record stays valid.

See how to choose a compound index for queries or revisit the related KeplerGrid walkthrough.