KeplerGrid guide

Combine MongoDB filters with $and and $or

To find open cases that are urgent or belong to the operations team, keep the status requirement outside the $or. Every match must pass the status check and at least one of the two alternatives.

Require open status and one alternative

Load the eight synthetic cases, open keplergrid_filter_lab.cases, and select Documents. Replace the text in Filter with this object and select Run.

{
  "status": "open",
  "$or": [
    { "priority": "urgent" },
    { "team": "ops" }
  ]
}

The filter matches CASE-101, CASE-102, and CASE-104. MongoDB combines status and $or with an implicit AND. The urgent case CASE-103 is closed and stays out of the result.

Make the AND grouping explicit

When building a filter from separate condition objects, put each required condition in the $and array. The $or object stays together as one condition. Both versions return the same three cases.

{
  "$and": [
    { "status": "open" },
    {
      "$or": [
        { "priority": "urgent" },
        { "team": "ops" }
      ]
    }
  ]
}

Spot a filter that returns too much

Compare this version. Adding status to the $or lets any one of the three checks qualify a case.

{
  "$or": [
    { "status": "open" },
    { "priority": "urgent" },
    { "team": "ops" }
  ]
}

It returns six cases, including the closed urgent case CASE-103 and the open non-urgent support case CASE-105. To debug the grouping on larger data, compare the result IDs or count all documents that match each filter.

See more query filter examples for dates, text, and ObjectIds.

Next, Compare two MongoDB fields with $expr.