KeplerGrid guide

Find MongoDB arrays by length with $size

Use the $size query operator for an exact array length. For a minimum length, guard the aggregation $size expression so it runs only on arrays.

Load eight synthetic cases

Save the following as practice-cases.jsonl and import it into an empty keplergrid_filter_lab.cases collection on a disposable MongoDB server. Open the collection in Documents with a Read only connection for the queries.

{"_id":"CASE-101","status":"open","priority":"urgent","team":"ops","tags":["billing","email"],"slaHours":{"$numberInt":"12"}}
{"_id":"CASE-102","status":"open","priority":"low","team":"ops","tags":["billing"],"slaHours":"12"}
{"_id":"CASE-103","status":"closed","priority":"urgent","team":"ops","tags":["billing","email","vip"],"slaHours":{"$numberDecimal":"12.50"}}
{"_id":"CASE-104","status":"open","priority":"urgent","team":"support","tags":[],"slaHours":null}
{"_id":"CASE-105","status":"open","priority":"medium","team":"support"}
{"_id":"CASE-106","status":"closed","priority":"low","team":"support","tags":null,"slaHours":[{"$numberInt":"12"}]}
{"_id":"CASE-107","status":"open","priority":"medium","team":"support","tags":"billing","slaHours":true}
{"_id":"CASE-108","status":"closed","priority":"low","team":"support","tags":["email","vip"],"slaHours":{"$numberInt":"20"}}

Match an exact array length

Paste this into Filter and select Run. CASE-101 and CASE-108 each have two tags. CASE-103 has three and stays out of the result.

{ "tags": { "$size": 2 } }

Switch to JSON view to see that the query returns each complete matching array.

Find empty arrays

Change the length to zero. This returns CASE-104. Its tags field is an empty array. The cases with a missing field, null, or a string do not qualify.

{ "tags": { "$size": 0 } }

Find arrays with at least two items

Use $expr to compare an array’s length to a threshold. $cond checks $isArray before evaluating $size. Other field values take the false branch.

{
  "$expr": {
    "$cond": [
      { "$isArray": "$tags" },
      { "$gte": [{ "$size": "$tags" }, 2] },
      false
    ]
  }
}

The result includes CASE-101, CASE-103, and CASE-108. Test a narrow filter first on a large collection. An index cannot answer the $size part of the exact-length query, although other predicates may use indexes.

To match specific elements instead of a length, compare $in and $all.

Next, Find shared MongoDB array values with $setIntersection.