0PricingLogin
MongoDB Academy · Lesson

Querying Arrays: $all, $size, and Element Match

Learners will filter documents by array contents using $all for multi-element matching and $size for length checks.

Arrays as First-Class Citizens

In MongoDB, arrays are a native BSON type that can be stored directly in a document field. Unlike relational databases where arrays require a separate junction table, MongoDB lets you embed arrays of any type—scalars, sub-documents, or mixed—directly in the document. This makes arrays one of the most useful features but also one of the most nuanced to query correctly.

// Documents with array fields
db.products.insertMany([
  { name: 'Laptop', tags: ['electronics', 'computers', 'portable'] },
  { name: 'Mouse', tags: ['electronics', 'peripherals'] },
  { name: 'Book', tags: ['education', 'reading'] }
]);

Simple Array Equality Queries

A simple equality filter on an array field checks whether the array contains the specified value as an element. You don't need a special operator—just write the filter as if the field were a scalar. MongoDB will match any document where the array contains that exact value anywhere in it.

// Find products tagged 'electronics'
// MongoDB checks if 'electronics' is an element of the tags array
db.products.find({ tags: 'electronics' });
// Returns Laptop and Mouse (both have 'electronics' in tags)

// This also works on arrays of numbers
db.scores.find({ values: 95 });
// Matches { values: [80, 95, 72] }

All lessons in this course

  1. Querying Arrays: $all, $size, and Element Match
  2. $elemMatch: Matching Array Sub-Documents
  3. Updating Arrays: $push, $pull, $pop, $addToSet
  4. Positional and Filtered Positional Updates
← Back to MongoDB Academy