0Pricing
MongoDB Academy · 강의

배열 쿼리하기: $all, $size, 요소 일치

학습자는 여러 요소 일치에는 $all을, 길이 확인에는 $size를 사용해 배열 내용으로 문서를 필터링합니다.

배열 쿼리하기: $all, $size, 요소 일치은(는) CoddyKit의 무료 MongoDB Academy 강의입니다. 이것은 4개 중 1번째 강의입니다. 아래에서 전체 강의를 무료로 읽을 수 있으며, 내장 코드 에디터와 24/7 AI 튜터와 함께 브라우저에서 직접 실습할 수 있습니다. 이 강의는 MongoDB Academy 학습 경로의 일부이며, 진행 상황이 웹과 CoddyKit 앱에 동기화됩니다. MongoDB Academy 강의에는 총 4개의 강의가 포함되어 있습니다.

이 강의의 일부는 아직 번역되지 않았으며 영어로 표시됩니다.

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] }

The $all Operator

The $all operator matches documents where the array contains all of the specified values, in any order. Unlike a plain equality check (which matches a single element), $all enforces that every specified element is present. Think of it as multiple AND conditions on array membership.

// Find products tagged BOTH 'electronics' AND 'portable'
db.products.find({
  tags: { $all: ['electronics', 'portable'] }
});
// Returns Laptop (has both tags)
// Does NOT return Mouse (missing 'portable')

// Order of values in $all does not matter
db.products.find({
  tags: { $all: ['portable', 'electronics'] }  // same result
});

The $size Operator

The $size operator matches documents where the array field has exactly the specified number of elements. It accepts a literal integer—you cannot use range comparisons like $gt with $size directly. For range-based length checks, use a field that stores the array length alongside the array, or use an aggregation with $where.

// Find products with exactly 3 tags
db.products.find({ tags: { $size: 3 } });
// Returns Laptop (tags has 3 elements)

// $size does NOT support ranges:
// db.products.find({ tags: { $size: { $gt: 2 } } }); // INVALID

// Workaround: store the count as a field
db.products.updateMany({}, [{ $set: { tagCount: { $size: '$tags' } } }]);
db.products.find({ tagCount: { $gt: 2 } });  // range check on stored count

Matching by Array Index

You can query by a specific position in an array using dot notation with an index number. For example, { 'scores.0': 100 } matches documents where the first element of the scores array is 100. This is useful when array order is meaningful, such as a ranked list or time-ordered sequence.

// Documents: { name: 'Alice', scores: [100, 85, 92] }
//            { name: 'Bob',   scores: [75, 88, 91] }

// Find documents where the FIRST score is 100
db.results.find({ 'scores.0': 100 });
// Returns Alice

// Find where SECOND element is greater than 85
db.results.find({ 'scores.1': { $gt: 85 } });
// Returns Bob (scores[1] = 88 > 85) and Alice (85 is NOT > 85)

The Spread Field Problem

A subtle gotcha: when you filter an array of sub-documents with multiple conditions on different fields, MongoDB applies each condition independently across all array elements—not to a single element. This is called the spread field problem. For example, { 'scores.value': { $gt: 90 }, 'scores.grade': 'A' } matches if any element has value > 90 AND any element has grade 'A'—they don't have to be the same element.

// Documents:
// { scores: [{ value: 95, grade: 'A' }, { value: 60, grade: 'D' }] }
// { scores: [{ value: 92, grade: 'B' }, { value: 72, grade: 'C' }] }

// This filter has SPREAD FIELD issue:
// Matches doc1 (value 95>90 is in scores[0], grade 'A' is in scores[0] - fine here)
// Also matches doc2 if value 92>90 from one element + some 'B'... but what if:
// { scores: [{ value: 91, grade: 'B' }, { value: 62, grade: 'A' }] }
// This would ALSO match! 91 > 90 from element[0] + grade 'A' from element[1]

$elemMatch for Multi-Condition Array Queries

The $elemMatch query operator solves the spread field problem by requiring all conditions to be satisfied by the same single array element. Wrap your conditions in { $elemMatch: { condition1, condition2 } } and MongoDB will only return documents where at least one array element satisfies all the specified conditions simultaneously.

// Find documents where a SINGLE scores element has value > 90 AND grade 'A'
db.results.find({
  scores: {
    $elemMatch: {
      value: { $gt: 90 },
      grade: 'A'
    }
  }
});
// Only matches if one element has BOTH value > 90 AND grade 'A'

$elemMatch for Scalar Arrays

$elemMatch can also be applied to arrays of scalar values (strings, numbers) when you need to apply multiple operators to the same element. For example, finding elements that are both greater than 10 and less than 20—without $elemMatch, these conditions could be satisfied by two different elements.

// Find docs where a SINGLE element is between 10 and 20
db.measurements.find({
  values: { $elemMatch: { $gt: 10, $lt: 20 } }
});
// { values: [5, 15, 25] } - matches (15 satisfies both)
// { values: [5, 30] }     - does NOT match

// Without $elemMatch (wrong - tests across elements):
db.measurements.find({ values: { $gt: 10, $lt: 20 } });
// { values: [5, 30] } WOULD match! (5 < 20, 30 > 10, different elements)

Combining $all and $elemMatch

You can use $all with $elemMatch expressions inside it to require multiple complex conditions across multiple distinct array elements. Each $elemMatch inside $all must be satisfied by a different element. This pattern is rarely needed but is available for complex multi-condition, multi-element requirements.

// Find docs where:
// - one element satisfies { value: { $gt: 90 }, grade: 'A' }
// - AND another element satisfies { value: { $lt: 70 }, grade: 'D' }
db.results.find({
  scores: {
    $all: [
      { $elemMatch: { value: { $gt: 90 }, grade: 'A' } },
      { $elemMatch: { value: { $lt: 70 }, grade: 'D' } }
    ]
  }
});

Arrays and Index Behaviour

An index on an array field automatically becomes a multikey index in MongoDB, with one index entry per array element. This means queries like { tags: 'electronics' } and { tags: { $all: ['electronics', 'portable'] } } both benefit from the index. However, a compound index cannot have multikey on more than one array field per document—attempting to do so throws an error.

// Index on tags field becomes multikey automatically
db.products.createIndex({ tags: 1 });

// These queries all use the multikey index efficiently:
db.products.find({ tags: 'electronics' });
db.products.find({ tags: { $all: ['electronics', 'portable'] } });
db.products.find({ tags: { $size: 3 } });
// Note: $size cannot use the index for size filtering
// (it still needs to check document-level array length)

Using explain() With Array Queries

Array queries with $all and $elemMatch can sometimes surprise you with their index usage. Always verify with explain('executionStats'). A $size filter will show IXSCAN on the multikey index but still examine all index entries (since size is not stored in the index). An $elemMatch on indexed fields will use IXSCAN on the matching element conditions.

// Check how array queries use indexes
db.products.find({
  tags: { $all: ['electronics', 'portable'] }
}).explain('executionStats');

// Look for:
// stage: 'IXSCAN' - index is being used
// totalKeysExamined vs nReturned ratio

Quick Check

Test your understanding of array query operators in MongoDB.

Lesson Recap

In this lesson you learned: $all requires an array to contain all specified values, $size matches arrays with an exact number of elements, and $elemMatch ensures multiple conditions apply to the same single array element, solving the spread field problem. Next up we dive deeper into $elemMatch for matching array sub-documents.

자주 묻는 질문

“배열 쿼리하기: $all, $size, 요소 일치” 강의는 무료인가요?

네 — “배열 쿼리하기: $all, $size, 요소 일치” 전체 내용을 이 웹사이트에서 무료로 읽을 수 있습니다. 인터랙티브하게 실습하려면(내장 코드 에디터와 24/7 AI 튜터), CoddyKit PRO로 업그레이드하면 MongoDB Academy 강의 전체를 잠금 해제할 수 있습니다. MongoDB Academy 강의에는 총 4개의 강의가 포함되어 있습니다.

“배열 쿼리하기: $all, $size, 요소 일치”에서 뭘 배우나요?

학습자는 여러 요소 일치에는 $all을, 길이 확인에는 $size를 사용해 배열 내용으로 문서를 필터링합니다. 브라우저에서 직접 실행하는 실습 코드로 MongoDB Academy을(를) 배우며, 24/7 AI 튜터가 강의를 진행하면서 질문에 답변해줍니다.

MongoDB Academy을(를) 시작하는 데 경험이 필요한가요?

사전 경험은 필요하지 않습니다. CoddyKit의 MongoDB Academy은(는) 초급자부터 고급 학습자까지를 위해 구성되어 있으므로, 여기서 시작하거나 처음부터 시작할 수 있으며 자신의 속도대로 진행할 수 있습니다. 이것은 4개 중 1번째 강의입니다.

“배열 쿼리하기: $all, $size, 요소 일치” 강의는 얼마나 걸리나요?

대부분의 CoddyKit 강의는 약 5~10분이 소요됩니다. 각 강의는 간결하고 인터랙티브하여 꾸준한 진행이 가능하며, 웹과 앱에서 중단한 부분부터 바로 시작할 수 있습니다.

이 MongoDB Academy 강의에서 코드를 작성하고 실행할 수 있나요?

네. 모든 MongoDB Academy 강의에는 내장 코드 에디터가 포함되어 있으므로, 브라우저에서 바로 실제 코드를 작성하고 실행한 후 즉시 AI 피드백을 받을 수 있습니다 — 로컬 설정이 필요 없습니다.

이 강의의 모든 강의

  1. 배열 쿼리하기: $all, $size, 요소 일치
  2. $elemMatch: 배열 하위 문서 일치시키기
  3. 배열 업데이트하기: $push, $pull, $pop, $addToSet
  4. 위치 지정 및 필터링된 위치 지정 업데이트
← MongoDB Academy(으)로 돌아가기