0Pricing
MongoDB Academy · 강의

$ 및 $elemMatch 배열 프로젝션

$ 및 $elemMatch 프로젝션을 사용하여 일치하는 첫 배열 요소만 반환하거나 필터링된 하위 배열을 반환합니다.

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

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

The Problem: Returning Only One Array Element

Sometimes a query matches a document based on an array element—for example, finding an order that contains a specific product—but you only want the matching array element returned, not the entire array. The standard inclusion projection returns all elements of the array. MongoDB provides two special array projection operators to solve this: the positional $ operator and $elemMatch.

The $ Positional Operator

The $ positional projection operator returns the first element of an array that matches the query condition. It is placed in the projection where the array field name normally goes. The condition that matched in the filter is automatically used to determine which element to project. Only one $ can appear in a single projection.

// Find the order and return only the matching line item
db.orders.findOne(
  { 'items.productId': ObjectId('p1') },
  { projection: { 'items.$': 1 } }
);
// Result: { _id: ..., items: [{ productId: ObjectId('p1'), qty: 2, price: 9.99 }] }
// Only the FIRST matching element is returned

How $ Matches the Filter Condition

The $ operator uses the filter condition on the array field from the query to identify which element to return. The query filter must include a condition on the same array field that appears in the projection. If the filter matches multiple elements, only the first match (by array order) is returned. This is an important limitation to keep in mind.

// Filter on items.qty, project only that matching item
db.orders.find(
  { 'items.qty': { $gt: 1 } },
  { projection: { 'items.$': 1, total: 1 } }
);
// Returns the first item in the items array where qty > 1
// If multiple items have qty > 1, only the first one is projected

$ Operator Limitations

The $ positional operator has two key limitations: (1) it only returns the first matching element, even if multiple elements satisfy the filter; (2) the array field must appear in the query filter (you cannot project a field with $ that was not part of the filter condition). For multi-condition or multi-element matching, use $elemMatch in the projection instead.

The $elemMatch Projection Operator

$elemMatch in a projection returns only the first array element that matches the specified conditions, similar to the $ operator but with one key difference: the filter conditions are specified directly in the projection, not in the query filter. This lets you project a matching element from an array even when the main query filter uses different criteria.

// Find all orders, but from the items array return only the item with qty > 1
db.orders.find(
  { status: 'shipped' },  // main filter on a different field
  {
    projection: {
      total: 1,
      items: { $elemMatch: { qty: { $gt: 1 } } }  // array filter in projection
    }
  }
);
// items array is present only if an element matches; absent if none match

$ vs $elemMatch: The Key Difference

The core difference:

  • $ in projection: the match condition comes from the query filter. Requires the array field to appear in the filter.
  • $elemMatch in projection: you write a separate condition inside the projection itself. The main filter can be on any field.
Both return only the first matching element. Use $ when the filter condition is already on the array field; use $elemMatch projection when you need a different condition or the filter is on a different field.

$elemMatch With Multiple Conditions

$elemMatch in the projection can apply multiple conditions to a sub-document within the array—conditions that must all be satisfied by the same array element. This is critical for sub-documents: without $elemMatch, MongoDB evaluates conditions across different elements and can return false positives.

// From orders, return only items where qty > 1 AND price < 20
db.orders.find(
  { status: 'delivered' },
  {
    projection: {
      items: {
        $elemMatch: {
          qty: { $gt: 1 },
          price: { $lt: 20 }
        }
      }
    }
  }
);
// Both conditions must match the SAME array element

Absent Array Field When No Element Matches

When using $elemMatch in a projection and no array element satisfies the condition, the array field is entirely absent from the result document (not present as an empty array). This means your application code must handle the case where the projected array field may be undefined. Always check for the field's existence before accessing its elements.

const order = await db.collection('orders').findOne(
  { status: 'shipped' },
  { projection: { items: { $elemMatch: { qty: { $gt: 100 } } } } }
);

// Safe access — items may be absent if no element matched
const matchedItem = order.items ? order.items[0] : null;
console.log('Matched item:', matchedItem);

Combining $elemMatch With Other Projections

You can combine an $elemMatch array projection with regular field projections in the same query. Project scalar fields with their usual inclusion syntax and apply $elemMatch only on the array field. Remember the cannot-mix rule: all non-array fields must use the same mode (inclusion or exclusion).

// Project total and status (inclusion) + first matching item
db.orders.findOne(
  { customerId: ObjectId('c1') },
  {
    projection: {
      total: 1,
      status: 1,
      _id: 0,
      items: { $elemMatch: { qty: { $gt: 0 } } }
    }
  }
);

$elemMatch in the Query Filter vs Projection

Be careful not to confuse $elemMatch in the query filter (which matches documents) with $elemMatch in the projection (which selects which element to return). The filter form determines which documents are returned; the projection form determines which array elements appear in those documents. They are often used together but serve different purposes.

// $elemMatch in FILTER: find orders containing a specific item
db.orders.find({
  items: { $elemMatch: { productId: ObjectId('p1'), qty: { $gt: 1 } } }
});

// $elemMatch in PROJECTION: from all shipped orders, return only that matching item
db.orders.find(
  { status: 'shipped' },
  { projection: { items: { $elemMatch: { productId: ObjectId('p1'), qty: { $gt: 1 } } } } }
);

Real-World Use Case: User Scores

A gaming leaderboard document stores all scores for a player in an embedded array. When displaying a player's score for a specific game, you only want that game's score element, not the entire score history. $elemMatch in the projection targets exactly that element, keeping the response small even if the player has thousands of game scores recorded.

db.players.find(
  { username: 'gamer42' },
  {
    projection: {
      username: 1,
      scores: { $elemMatch: { gameId: 'chess_blitz' } },
      _id: 0
    }
  }
);
// Result: { username: 'gamer42', scores: [{ gameId: 'chess_blitz', score: 1540 }] }

Quick Check

Test your understanding of MongoDB & NoSQL Databases concepts from this lesson.

Lesson Recap

In this lesson you learned: the $ positional operator returns the first element that matched the query filter condition, $elemMatch in projection lets you specify match conditions independently of the query filter, and if no element matches $elemMatch, the field is absent from the result. Next up we look at projection best practices for API responses.

자주 묻는 질문

“$ 및 $elemMatch 배열 프로젝션” 강의는 무료인가요?

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

“$ 및 $elemMatch 배열 프로젝션”에서 뭘 배우나요?

$ 및 $elemMatch 프로젝션을 사용하여 일치하는 첫 배열 요소만 반환하거나 필터링된 하위 배열을 반환합니다. 브라우저에서 직접 실행하는 실습 코드로 MongoDB Academy을(를) 배우며, 24/7 AI 튜터가 강의를 진행하면서 질문에 답변해줍니다.

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

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

“$ 및 $elemMatch 배열 프로젝션” 강의는 얼마나 걸리나요?

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

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

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

이 강의의 모든 강의

  1. 포함 및 제외 프로젝션 비교
  2. 중첩 및 배열 필드 프로젝션
  3. $ 및 $elemMatch 배열 프로젝션
  4. API 응답을 위한 프로젝션 모범 사례
← MongoDB Academy(으)로 돌아가기