KeplerGrid guide

Query MongoDB arrays with $elemMatch

Use $elemMatch to find products with at least five units in the east warehouse. A filter with two separate dot-notation conditions can take the warehouse from one array element and the quantity from another.

Set up the synthetic inventory

Run this once in mongosh against a development MongoDB instance. The keplergrid_inventory.inventory collection should be empty. The same three documents also work for the null, projection, and typed editing guides.

const scratch = db.getSiblingDB("keplergrid_inventory")
scratch.inventory.insertMany([
  {
    _id: "SKU-100",
    name: "Notebook",
    category: "paper",
    stock: [
      { warehouse: "east", quantity: 8 },
      { warehouse: "west", quantity: 1 }
    ],
    reorderNote: null,
    pricing: { unitPrice: Decimal128("12.50"), currency: "USD" }
  },
  {
    _id: "SKU-200",
    name: "Pencils",
    category: "writing",
    stock: [
      { warehouse: "east", quantity: 2 },
      { warehouse: "west", quantity: 12 }
    ],
    pricing: { unitPrice: Decimal128("4.25"), currency: "USD" }
  },
  {
    _id: "SKU-300",
    name: "Envelopes",
    category: "paper",
    stock: [{ warehouse: "west", quantity: 4 }],
    reorderNote: "Review next week",
    pricing: { unitPrice: Decimal128("7.20"), currency: "USD" }
  }
])

Compare two filters in KeplerGrid

Connect to the development instance in Read only mode. Open keplergrid_inventory.inventory in Documents. Paste this filter and click Run.

{ "stock.warehouse": "east", "stock.quantity": { "$gte": 5 } }

The practice collection returns SKU-100 and SKU-200. The pencils qualify because the east entry has the requested warehouse and the west entry has enough units.

Replace the filter with this version and run it again.

{
  "stock": {
    "$elemMatch": { "warehouse": "east", "quantity": { "$gte": 5 } }
  }
}

Only SKU-100 remains. Its east entry satisfies both conditions together.

Check the array in the result

Select JSON view in the results toolbar to see each stock object together with its warehouse and quantity. The filter picks which product documents to return. The returned stock array still includes every entry in that document.

Try the MongoDB projection guide to choose which fields to return, or see more query filter examples.

To change the array returned for each document, filter and reshape its elements.

Update MongoDB array elements with arrayFilters