MongoDB Query: Array Size Greater Than 0, 1 or N

You need every MongoDB document whose array holds more than one item, or more than zero, and $size will not do it: it only accepts an exact number. The short answer: for “greater than N” test whether index N exists, with { "items.1": { $exists: true } } for size greater than 1 (use items.0 for greater than 0, items.2 for greater than 2). For any comparison on the real size, use $expr with $size and guard against fields that are not arrays.

Every query below was run against MongoDB 8.0.4 with mongosh 2.14.3. The C# filter ran with driver 3.14.1 on .NET SDK 10.0.401 and the Node.js query with the 7.9.1 driver. See the end for what was not tested.

Animation of seven test documents in a MongoDB orders collection showing which ones match array size greater than 0, 1 and 2, including documents where the field is missing, null or a string

Diagram built from the real mongosh results below, not a screenshot.

Which approach should you use?

GoalQueryNotes
Array has at least one item{ items: { $type: "array", $ne: [] } }Can use an index on the field
Size greater than N (small N){ "items.N": { $exists: true } }Simple. Scanned the whole collection in the test
Any comparison on size{ $expr: { $gt: [ { $size: "$items" }, N ] } }Errors if the field is not an array unless guarded
Query often and at scaleStore a count field and index itKeep it in sync on every write

Test data

Seven documents in shop.orders: arrays of 0, 1, 2 and 3 items, plus three documents with no array at all (field missing, null, and a string). The last three are what break naive queries.

db.orders.insertMany([
  { _id: "o1", items: [] },
  { _id: "o2", items: ["pen"] },
  { _id: "o3", items: ["pen", "ink"] },
  { _id: "o4", items: ["pen", "ink", "pad"] },
  { _id: "o5" },
  { _id: "o6", items: null },
  { _id: "o7", items: "pen" }
])

Query pattern: array size greater than 0 (not empty)

Approach I: the not-equal operator. The common answer is $ne: []. On its own it is wrong for this data, because documents with no array also satisfy it. Real results:

db.orders.find({ items: { $ne: [] } })                         // o2, o3, o4, o5, o6, o7
db.orders.find({ items: { $type: "array", $ne: [] } })        // o2, o3, o4

Add $type: "array" to restrict the match to real arrays (see $exists and the other query operators in the manual). Alternatively use the index form below: { "items.0": { $exists: true } } returned the same three documents.

Approach II: array size greater than 0, 1 or 2

Check that the element at position N exists. If item 1 exists, the array has at least two items:

db.orders.find({ "items.0": { $exists: true } })   // size > 0: o2, o3, o4
db.orders.find({ "items.1": { $exists: true } })   // size > 1: o3, o4
db.orders.find({ "items.2": { $exists: true } })   // size > 2: o4

These are the real results from the test. The three non-array documents never match. The approach is only practical for a small, fixed N.

$size itself is exact: { items: { $size: 2 } } returned only o3, and { items: { $size: { $gt: 1 } } } fails with Failed to parse $size. Expected a number. The $size query operator cannot take a range.

Any comparison with $expr and $size

Inside $expr you can use the aggregation $size with $gt, $gte or $lt. Run it unguarded and a document without an array stops the whole query: the test returned The argument to $size must be an array, but was of type: missing. Guard it:

db.orders.find({
  $expr: {
    $gt: [
      { $cond: [ { $isArray: "$items" }, { $size: "$items" }, 0 ] },
      1
    ]
  }
})   // o3, o4

To see the size as a field, use an aggregation. Real result: o3:2, o4:3.

db.orders.aggregate([
  { $match: { items: { $type: "array" } } },
  { $addFields: { itemCount: { $size: "$items" } } },
  { $match: { itemCount: { $gt: 1 } } },
  { $project: { itemCount: 1 } }
])

Make it fast: store the count

Neither $expr nor the positional exists form gave an index plan in the test. With an index on items, "items.1": { $exists: true } still showed a COLLSCAN, while { items: { $type: "array", $ne: [] } } used an IXSCAN through FETCH. (Seven documents is a plan check, not a benchmark.) For large collections, store the length and index it, then query the number:

db.orders.updateMany({ items: { $type: "array" } }, [ { $set: { itemCount: { $size: "$items" } } } ])
db.orders.createIndex({ itemCount: 1 })
db.orders.find({ itemCount: { $gt: 1 } })   // IXSCAN, o3 and o4

The cost is that every write that changes the array must also update itemCount.

C# driver and Node.js

In C#, SizeGt builds the positional form for you. With a document class that maps items:

var filter = Builders<Order>.Filter.SizeGt(o => o.Items, 1);
var hits = await orders.Find(filter).ToListAsync();

The driver sent { "items.1" : { "$exists" : true } } and returned o3, o4. If your collection holds documents with extra fields, add [BsonIgnoreExtraElements] to the class, otherwise deserialization throws. For setup and CRUD, see the MongoDB C# driver getting started guide.

In Node.js the filter is the same document:

const docs = await orders.find({ "items.1": { $exists: true } }).toArray();                 // o3, o4
const agg = await orders.aggregate([
  { $match: { items: { $type: "array" } } },
  { $match: { $expr: { $gt: [{ $size: "$items" }, 1] } } },
]).toArray();                                                                             // o3, o4

Common errors and what was tested

  • $size must be an array. The unguarded $expr query fails on missing fields. Add $type: "array" or the $isArray guard.
  • Expected a number. $size does not accept $gt. Use the positional form or $expr.
  • Too many results. $ne: [] alone matches documents with no array. Add the type check.
  • Case and string matching inside array items is a separate topic, see MongoDB case-sensitive and case-insensitive queries.
  • Tested: all mongosh queries on MongoDB 8.0.4, the C# filter (driver 3.14.1) and the Node.js queries (driver 7.9.1) against a local server. Not tested: other server versions, sharded clusters, Atlas, and large collections (performance comparisons were not measured).

Summary

  • Size greater than N: { "field.N": { $exists: true } }.
  • Not empty: { field: { $type: "array", $ne: [] } }.
  • Any comparison: $expr with $size, guarded by $isArray.
  • At scale: store and index a count field.

Further reading: $size (MongoDB manual), $size aggregation operator (MongoDB manual) and $expr (MongoDB manual). Working with dates next? See MongoDB date range queries.

Found this useful?

Bookmark this page and share it with your team. Get new .NET, cloud and database tutorials in your inbox.

FAQ

How do I query MongoDB for an array size greater than 1?

Use { “items.1”: { $exists: true } }, which matches documents whose array has an element at index 1, so at least two items. For a computed comparison use $expr with $gt and $size, and guard non-array fields with $isArray.

Why does $size not work with $gt?

The $size query operator only takes an exact number, so { $size: { $gt: 1 } } fails with ‘Expected a number’. Inside $expr the aggregation $size returns the length and can be compared with $gt, $gte or $lt.

How do I find documents where an array is not empty?

Use { items: { $type: “array”, $ne: [] } }. Without the type check, { items: { $ne: [] } } also matches documents where the field is missing, null or not an array.

Leave a Reply

Your email address will not be published. Required fields are marked *