KeplerGrid guide

Compare two MongoDB fields with $expr

Find documents where one field exceeds another. Use numeric guards to exclude incomplete or string-valued records.

Load the practice collection

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

const lab = db.getSiblingDB("keplergrid_practice")
lab.budgets.insertMany([
  { _id: "design", spent: 125, budget: 100 },
  { _id: "hosting", spent: 80, budget: 100 },
  { _id: "tools", spent: 100, budget: 100 },
  { _id: "training", spent: 30 },
  { _id: "travel", spent: "125", budget: 100 }
])

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

Find expenses over their own budget

Paste this object into the Documents filter. Inside the expression, a string starting with $ reads a field from the current document.

{
  "$expr": { "$and": [
    { "$isNumber": "$spent" },
    { "$isNumber": "$budget" },
    { "$gt": ["$spent", "$budget"] }
  ] }
}

Only design matches. The numeric guards exclude training and travel. Changing $gt to $gte also includes the equal pair tools.

Narrow the candidates before comparing

If you check a fixed period or team, add that predicate alongside $expr where an appropriate index can use it. The field-to-field comparison still evaluates candidate documents.

See how to calculate a new value for each result or revisit the related KeplerGrid walkthrough.