Bird
Raised Fist0
MongoDBquery~15 mins

$all operator for matching all elements in MongoDB - Deep Dive

Choose your learning style10 modes available

Start learning this pattern below

Jump into concepts and practice - no test required

or
Recommended
Test this pattern10 questions across easy, medium, and hard to know if this pattern is strong
Overview - $all operator for matching all elements
What is it?
The $all operator in MongoDB is used to find documents where an array field contains all the specified elements. It checks if every element in the query list is present in the array, regardless of order or extra elements. This helps filter documents based on multiple required values inside arrays.
Why it matters
Without $all, it would be hard to find documents that contain multiple specific items in an array, especially when order doesn't matter. This operator solves the problem of matching all required elements efficiently, making queries more precise and useful in real applications like tags, categories, or skills filtering.
Where it fits
Before learning $all, you should understand basic MongoDB queries and how arrays work in documents. After mastering $all, you can explore more complex array query operators like $elemMatch, $in, and aggregation pipeline stages for advanced filtering.
Mental Model
Core Idea
The $all operator matches documents whose array field contains every element listed in the query, no matter the order or extra items.
Think of it like...
Imagine you have a shopping list and you want to find all baskets that contain every item on your list, even if the baskets have extra things you don't need.
Document array field: [apple, banana, orange, grape]
Query with $all: {$all: [banana, orange]}
Result: Match because both banana and orange are in the array

┌───────────────┐
│ Document      │
│ array:       │
│ [apple,      │
│  banana,     │
│  orange,     │
│  grape]      │
└───────────────┘
       ↑
       │
Query: {$all: [banana, orange]}
       ↓
Match: Yes
Build-Up - 7 Steps
1
FoundationUnderstanding MongoDB Arrays
🤔
Concept: Learn what arrays are in MongoDB documents and how they store multiple values.
In MongoDB, a field can hold an array, which is a list of values. For example, a document might have a field 'tags' with ['red', 'blue', 'green']. Arrays let you store multiple related items in one field.
Result
You can store and retrieve multiple values in a single field inside documents.
Knowing arrays are just lists inside documents helps you understand why special operators like $all are needed to query them.
2
FoundationBasic Array Query with $in Operator
🤔
Concept: Learn how to find documents where an array contains at least one of several values using $in.
The $in operator matches documents where the array has any one of the specified values. For example, {tags: {$in: ['red', 'yellow']}} finds documents with 'red' or 'yellow' in tags.
Result
Documents with at least one matching element in the array are returned.
Understanding $in shows the difference between matching any element versus matching all elements.
3
IntermediateIntroducing $all for Matching Every Element
🤔Before reading on: do you think $all matches documents with any or all specified elements? Commit to your answer.
Concept: $all matches documents where the array contains every element listed, not just some.
Using $all, you specify a list of elements, and MongoDB returns documents whose array contains all those elements. For example, {tags: {$all: ['red', 'blue']}} finds documents where tags include both 'red' and 'blue'.
Result
Only documents with all specified elements in the array are matched.
Knowing $all requires every element helps you filter precisely when multiple criteria must be met inside arrays.
4
IntermediateOrder and Extra Elements Don't Matter
🤔
Concept: $all does not care about the order of elements or if the array has more items than specified.
If a document's array is ['blue', 'red', 'green'], a query with {$all: ['red', 'blue']} matches because both elements are present, even though order differs and 'green' is extra.
Result
Documents match as long as all elements are present, regardless of order or extra items.
Understanding this prevents confusion about why some documents match even if arrays look different.
5
IntermediateUsing $all with Nested Conditions
🤔Before reading on: can $all be combined with other operators like $elemMatch? Commit to your answer.
Concept: $all can be combined with $elemMatch to match complex conditions on array elements.
You can use $all with $elemMatch to require multiple conditions on different elements. For example, {scores: {$all: [{$elemMatch: {score: {$gt: 80}}}, {$elemMatch: {score: {$lt: 50}}}]}} finds documents with scores array containing at least one score > 80 and one < 50.
Result
Documents matching all specified element conditions are returned.
Knowing how to combine $all with $elemMatch unlocks powerful queries on arrays with complex criteria.
6
AdvancedPerformance Considerations with $all
🤔Before reading on: do you think $all queries are always fast? Commit to your answer.
Concept: $all queries can be slow without proper indexes because MongoDB must check multiple elements in arrays.
To speed up $all queries, create multikey indexes on the array field. MongoDB uses these indexes to quickly find documents containing all specified elements. Without indexes, queries scan many documents, slowing performance.
Result
Proper indexing makes $all queries efficient even on large collections.
Understanding indexing needs prevents performance bottlenecks in production systems using $all.
7
ExpertSubtle Behavior with Duplicate Elements in Arrays
🤔Before reading on: does $all require the array to have duplicates if the query lists duplicates? Commit to your answer.
Concept: When $all query lists duplicate elements, the array must contain at least that many occurrences of each element.
For example, {tags: {$all: ['red', 'red']}} matches only documents where 'tags' array has 'red' at least twice. If the array has only one 'red', it won't match.
Result
Duplicate elements in $all queries enforce minimum counts in arrays.
Knowing this subtlety helps avoid unexpected query results when duplicates appear in $all conditions.
Under the Hood
MongoDB uses multikey indexes on array fields to track each element's presence. When a $all query runs, MongoDB checks the index for each element in the $all list and intersects the sets of matching documents. This intersection ensures only documents containing all elements are returned. Without indexes, MongoDB scans documents and checks arrays manually.
Why designed this way?
The $all operator was designed to efficiently handle queries requiring multiple elements in arrays without caring about order. Using set intersection on indexes is faster than scanning all documents. Alternatives like multiple $in queries would not guarantee all elements are present, so $all fills this gap.
┌───────────────┐       ┌───────────────┐       ┌───────────────┐
│ Index for 'red'│──────▶│ Index for 'blue'│──────▶│ Intersection  │
└───────────────┘       └───────────────┘       │ of doc sets   │
                                                  └───────────────┘
                                                         ↓
                                                  ┌───────────────┐
                                                  │ Matching docs │
                                                  └───────────────┘
Myth Busters - 4 Common Misconceptions
Quick: Does $all match documents if only some elements are present? Commit yes or no.
Common Belief:People often think $all matches if any one of the elements is present in the array.
Tap to reveal reality
Reality:$all requires every element in the query list to be present in the array for a match.
Why it matters:Misunderstanding this leads to incorrect query results, returning documents that don't fully meet criteria.
Quick: Does the order of elements in $all query affect matching? Commit yes or no.
Common Belief:Some believe $all matches only if elements appear in the same order as in the query.
Tap to reveal reality
Reality:$all ignores order; it only checks presence of all elements regardless of sequence.
Why it matters:Expecting order sensitivity causes confusion when documents match unexpectedly.
Quick: If $all query lists duplicates, does the array need duplicates too? Commit yes or no.
Common Belief:Many think duplicates in $all query don't affect matching; one occurrence suffices.
Tap to reveal reality
Reality:The array must contain at least as many occurrences of each element as listed in $all.
Why it matters:Ignoring this causes missed matches or unexpected misses in queries with repeated elements.
Quick: Can $all be used to match complex conditions on array elements? Commit yes or no.
Common Belief:Some think $all only works with simple values, not with $elemMatch or conditions.
Tap to reveal reality
Reality:$all can combine with $elemMatch to match multiple complex conditions on array elements.
Why it matters:Not knowing this limits the power of queries and leads to more complicated or inefficient workarounds.
Expert Zone
1
When $all query contains duplicates, MongoDB enforces minimum counts of those elements in arrays, which can cause subtle bugs if unnoticed.
2
Multikey indexes used by $all queries can increase index size and impact write performance, so index design must balance read and write needs.
3
Combining $all with $elemMatch allows matching multiple complex conditions on different array elements, enabling powerful and precise queries.
When NOT to use
$all is not suitable when you want to match arrays containing any one of multiple elements; use $in instead. For matching elements with multiple conditions on the same array element, $elemMatch alone is better. For very large arrays or complex queries, aggregation pipelines with $filter may be more efficient.
Production Patterns
In real systems, $all is commonly used to filter documents by tags, skills, or categories where all specified criteria must be met. It is often combined with multikey indexes for performance. Developers also use $all with $elemMatch to query arrays of embedded documents with multiple conditions.
Connections
Set Theory
Builds-on
Understanding $all as a set intersection operation helps grasp how MongoDB finds documents containing all specified elements.
Boolean Logic
Same pattern
$all behaves like a logical AND across array elements, requiring all conditions to be true for a match.
Inventory Management
Analogy in practice
Just like checking if a warehouse has all items on a shipment list, $all verifies presence of all required elements in data arrays.
Common Pitfalls
#1Expecting $all to match if only some elements are present.
Wrong approach:{ tags: { $all: ['red', 'blue'] } } // returns documents with only 'red' or only 'blue'
Correct approach:{ tags: { $all: ['red', 'blue'] } } // returns only documents with both 'red' and 'blue'
Root cause:Misunderstanding that $all requires every element, not just any.
#2Assuming order matters in $all queries.
Wrong approach:{ tags: { $all: ['red', 'blue'] } } // expecting no match if array is ['blue', 'red']
Correct approach:{ tags: { $all: ['red', 'blue'] } } // matches regardless of order
Root cause:Confusing $all with ordered array matching.
#3Ignoring duplicate elements in $all query.
Wrong approach:{ tags: { $all: ['red', 'red'] } } // matches documents with only one 'red'
Correct approach:{ tags: { $all: ['red', 'red'] } } // matches only documents with at least two 'red's
Root cause:Not realizing $all enforces minimum counts for duplicates.
Key Takeaways
$all matches documents whose array fields contain every element specified, regardless of order or extra elements.
It differs from $in, which matches if any one element is present, making $all useful for precise multi-element filtering.
Proper indexing with multikey indexes is essential for efficient $all queries on large collections.
Duplicate elements in $all queries require arrays to have at least that many occurrences, a subtlety often overlooked.
Combining $all with $elemMatch enables powerful queries on arrays of embedded documents with multiple conditions.

Practice

(1/5)
1.

What does the $all operator do in MongoDB queries?

easy
A. Matches documents where an array contains any one of the specified values.
B. Matches documents where an array contains all specified values.
C. Matches documents where an array contains exactly one specified value.
D. Matches documents where an array is empty.

Solution

  1. Step 1: Understand the purpose of $all

    The $all operator is used to find documents where an array field contains all the values specified in the query.
  2. Step 2: Compare with other operators

    Unlike $in which matches any value, $all requires all values to be present in the array.
  3. Final Answer:

    Matches documents where an array contains all specified values. -> Option B
  4. Quick Check:

    $all = all values present [OK]
Hint: Remember: $all means every value must be in the array [OK]
Common Mistakes:
  • Confusing $all with $in operator
  • Thinking $all checks order of elements
  • Assuming $all matches partial values
2.

Which of the following is the correct syntax to find documents where the tags array contains both "red" and "blue" using $all?

{ tags: { $all: ["red", "blue"] } }
easy
A. { tags: { $all: ["red", "blue"] } }
B. { tags: { $all: "red", "blue" } }
C. { tags: { $all: "red blue" } }
D. { tags: { $all: { "red", "blue" } } }

Solution

  1. Step 1: Check the correct structure for $all

    The $all operator requires an array of values to match all elements.
  2. Step 2: Validate each option's syntax

    { tags: { $all: ["red", "blue"] } } correctly uses an array with square brackets. Options A, B, and D use incorrect syntax for arrays or objects.
  3. Final Answer:

    { tags: { $all: ["red", "blue"] } } -> Option A
  4. Quick Check:

    Correct array syntax for $all [OK]
Hint: Use square brackets [] to list values inside $all [OK]
Common Mistakes:
  • Using curly braces {} instead of square brackets []
  • Passing values as separate arguments instead of an array
  • Using a string instead of an array for $all
3.

Given the collection documents:

[{ "colors": ["red", "green", "blue"] }, { "colors": ["red", "yellow"] }, { "colors": ["blue", "green", "red"] }]

What will the query { colors: { $all: ["red", "blue"] } } return?

medium
A. No documents
B. Document 2 only
C. Documents 1 and 3
D. All three documents

Solution

  1. Step 1: Check each document's colors array

    Document 1 has ["red", "green", "blue"] which includes both "red" and "blue". Document 2 has ["red", "yellow"] missing "blue". Document 3 has ["blue", "green", "red"] which includes both.
  2. Step 2: Apply $all condition

    The query matches documents where both "red" and "blue" are present, so documents 1 and 3 match.
  3. Final Answer:

    Documents 1 and 3 -> Option C
  4. Quick Check:

    Both arrays contain "red" and "blue" [OK]
Hint: Check each array contains all values, order doesn't matter [OK]
Common Mistakes:
  • Assuming order matters for $all
  • Including documents missing one value
  • Confusing $all with $in behavior
4.

Identify the error in this query that tries to find documents where features array contains both "wifi" and "parking":

{ features: { $all: "wifi", "parking" } }
medium
A. The field name should be inside quotes.
B. The values should be inside curly braces instead of quotes.
C. The query should use $in instead of $all.
D. The $all operator requires an array of values, not separate arguments.

Solution

  1. Step 1: Analyze the $all operator usage

    The $all operator expects a single array containing all values to match.
  2. Step 2: Identify the syntax error

    The query incorrectly passes two separate string arguments instead of an array. It should be { $all: ["wifi", "parking"] }.
  3. Final Answer:

    The $all operator requires an array of values, not separate arguments. -> Option D
  4. Quick Check:

    $all needs an array [OK]
Hint: Always wrap $all values in an array [] [OK]
Common Mistakes:
  • Passing multiple values without array brackets
  • Using $in when $all is needed
  • Misplacing quotes around field names
5.

You have a collection of documents with a field ingredients which is an array of strings. You want to find all recipes that contain both "flour" and "sugar", but not "nuts". Which query correctly uses $all and other operators to achieve this?

hard
A. { ingredients: { $all: ["flour", "sugar"], $nin: ["nuts"] } }
B. { ingredients: { $all: ["flour", "sugar", "nuts"] } }
C. { ingredients: { $in: ["flour", "sugar"], $nin: ["nuts"] } }
D. { ingredients: { $all: ["flour", "sugar"] }, ingredients: { $nin: ["nuts"] } }

Solution

  1. Step 1: Use $all to match both "flour" and "sugar"

    The $all operator ensures the array contains both these ingredients.
  2. Step 2: Use $nin to exclude "nuts"

    The $nin operator excludes documents where the array contains "nuts".
  3. Step 3: Combine both conditions correctly

    { ingredients: { $all: ["flour", "sugar"], $nin: ["nuts"] } } combines $all and $nin inside the same field query, which is valid MongoDB syntax.
  4. Final Answer:

    { ingredients: { $all: ["flour", "sugar"], $nin: ["nuts"] } } -> Option A
  5. Quick Check:

    All required and no excluded ingredients [OK]
Hint: Combine $all and $nin inside one field object [OK]
Common Mistakes:
  • Putting $all and $nin in separate objects for same field
  • Using $in instead of $all for required ingredients
  • Including excluded items inside $all array