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
- Querying Arrays: $all, $size, and Element Match
- $elemMatch: Matching Array Sub-Documents
- Updating Arrays: $push, $pull, $pop, $addToSet
- Positional and Filtered Positional Updates