0Pricing
MongoDB Academy · 강의

집계 파이프라인 최적화 팁

학습자는 $match와 $project를 앞부분으로 이동하고, $match 전에 $unwind를 사용하지 않으며, 대규모 정렬에는 allowDiskUse를 사용하도록 집계 파이프라인을 재구성합니다.

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

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

Aggregation Performance: The Big Picture

Aggregation pipelines can be expensive — they can scan millions of documents, build large in-memory structures, and block for seconds. The key to fast pipelines is applying data-reduction stages as early as possible so later stages work on the smallest possible dataset. MongoDB also has an internal optimizer that automatically reorders certain stages, but understanding manual optimizations gives you the most control.

Put $match Early: Filter Before You Transform

$match is MongoDB's filter stage. Placing it as early as possible in the pipeline reduces the number of documents that flow into every subsequent stage. If $match can use an index, it becomes an extremely fast first step. Even a $match without an index early in the pipeline is better than a late one — it avoids processing documents that will be discarded anyway.

// BAD: $group processes all 1M docs, then $match discards most
db.orders.aggregate([
  { $group: { _id: '$status', total: { $sum: '$amount' } } },
  { $match: { _id: 'pending' } }   // late match
])

// GOOD: $match first — only 'pending' docs enter $group
db.orders.aggregate([
  { $match: { status: 'pending' } },  // early match, uses index
  { $group: { _id: '$customerId', total: { $sum: '$amount' } } }
])

Put $project Early: Reduce Document Size

Use $project early to drop fields you will not need in later stages. Fewer fields per document means smaller in-memory representations flowing through the pipeline, reducing memory pressure and CPU time. Only project away fields you are certain are not needed — an over-aggressive early $project that drops a field used in a later stage will fail.

// Drop large, unused fields early
db.products.aggregate([
  { $match: { category: 'electronics' } },
  // Remove bulky description and image fields early
  { $project: { name: 1, price: 1, stock: 1 } },
  { $group: { _id: null, avgPrice: { $avg: '$price' } } }
])

Pipeline Optimizer: Auto-Rewrites

MongoDB's aggregation optimizer automatically applies several rewrites before executing your pipeline. Key auto-rewrites: 1) Merges consecutive $match stages into one. 2) Moves $match before $skip and $limit when possible. 3) Merges consecutive $limit stages. 4) Pushes $match before $lookup to filter before the join. Use explain() to see the optimized pipeline.

// View the optimizer's rewritten pipeline
db.orders.explain().aggregate([
  { $lookup: { from: 'customers', localField: 'customerId',
      foreignField: '_id', as: 'customer' } },
  { $match: { 'customer.country': 'US' } }
])
// Optimizer may push $match before $lookup if fields allow

Avoid $unwind Before $match

$unwind explodes an array into multiple documents — one per array element. If you place $match after $unwind, you pay the full cost of expansion before filtering. When possible, filter before the $unwind to reduce the number of array elements that need expansion. This can reduce document count by an order of magnitude on large arrays.

// BAD: unwind first creates N*arraySize docs, then filter
db.blogs.aggregate([
  { $unwind: '$tags' },
  { $match: { tags: 'mongodb' } }
])

// GOOD: filter the root document first, then unwind
db.blogs.aggregate([
  { $match: { tags: 'mongodb' } },  // uses index on tags array
  { $unwind: '$tags' },
  { $match: { tags: 'mongodb' } }   // refine after unwind
])

Index Coverage for $match and $sort

The first $match stage of a pipeline can use a collection index just like a find() query. The first $sort stage can also use an index to avoid an in-memory sort — but only if it appears before any stage that modifies the document shape (like $project or $group). Structure your pipelines so early $match and $sort stages benefit from indexes.

// Index supports $match and $sort at the start
db.events.createIndex({ userId: 1, createdAt: -1 })

db.events.aggregate([
  { $match: { userId: 'u123' } },       // uses index
  { $sort:  { createdAt: -1 } },         // uses index sort order
  { $limit: 20 },
  { $project: { _id: 0, type: 1, payload: 1 } }
])

allowDiskUse for Large Sorts

By default, each aggregation stage is limited to 100 MB of RAM. If a $sort, $group, or $bucket stage exceeds this limit, the pipeline fails with an error. Setting allowDiskUse: true lets the pipeline spill to disk, enabling arbitrarily large sorts at the cost of slower I/O. The right fix is usually to add an index or filter more aggressively before the sort.

// Allow spill to disk for large aggregations
db.events.aggregate(
  [
    { $match: { year: 2024 } },
    { $sort: { amount: -1 } },
    { $group: { _id: '$region', total: { $sum: '$amount' } } }
  ],
  { allowDiskUse: true }
)

$lookup Performance: Filter Before Joining

$lookup is the aggregation equivalent of a SQL JOIN and is one of the most expensive stages. To minimise cost: 1) Place $match before $lookup so fewer documents need joining. 2) Ensure the joined collection has an index on the foreignField. 3) Use the pipeline form of $lookup with a $match inside it to filter the joined results immediately.

// Ensure foreignField is indexed
db.customers.createIndex({ _id: 1 })  // usually already indexed

// Use pipeline $lookup with internal $match to reduce joined docs
db.orders.aggregate([
  { $match: { status: 'pending' } },
  { $lookup: {
    from: 'customers',
    let: { cid: '$customerId' },
    pipeline: [
      { $match: { $expr: { $eq: ['$_id', '$$cid'] } } },
      { $project: { name: 1, email: 1 } }   // trim early
    ],
    as: 'customer'
  }}
])

Use $limit Early in Pagination Pipelines

When building paginated list endpoints, push $limit as early as possible after the filter and sort. A pipeline that processes 100,000 documents through $lookup and $addFields before limiting to 20 is 5,000x more expensive than one that limits first. Keyset pagination with a range filter often eliminates the need for $skip entirely.

// Efficient pagination: limit BEFORE expensive stages
db.products.aggregate([
  { $match: { category: 'books' } },
  { $sort: { rating: -1 } },
  { $limit: 20 },              // limit early!
  { $lookup: { from: 'reviews',
    localField: '_id', foreignField: 'productId', as: 'reviews' } }
])

Pre-Compute With Materialised Views

For expensive aggregations that power dashboards or reports, consider materialised views using $merge or $out. Run the heavy aggregation on a schedule (e.g., every hour) and write results to a dedicated collection. Queries against the materialised view are cheap point-lookups instead of expensive pipeline scans. Atlas also supports On-Demand Materialised Views via triggers.

// Materialise daily revenue summary
db.orders.aggregate([
  { $match: { createdAt: { $gte: ISODate('2025-01-01') } } },
  { $group: { _id: '$region', revenue: { $sum: '$amount' } } },
  { $merge: {
    into: 'revenue_summary',
    whenMatched: 'replace',
    whenNotMatched: 'insert'
  }}
])

Profiling Aggregation Pipelines

Use .explain('executionStats') on an aggregate to see how many documents each stage emitted. Look for stages where nReturned drops sharply — that is where the real work happens. If a stage is still processing millions of documents, add a $match or improve the index before it. For Atlas, the Query Profiler also shows aggregation pipeline performance over time.

db.orders.explain('executionStats').aggregate([
  { $match: { status: 'shipped' } },
  { $group: { _id: '$region', total: { $sum: '$amount' } } },
  { $sort: { total: -1 } },
  { $limit: 10 }
])
// Check: nReturned per stage, executionTimeMillisEstimate

Quick Check

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

Lesson Recap

In this lesson you learned: push $match and $project as early as possible to minimize document volume in later stages, ensure the first $match and $sort use indexes to avoid collection scans and in-memory sorts, and use allowDiskUse for unavoidably large sorts, but prefer better indexes or earlier filters as the permanent fix. Next up we explore Atlas Data Federation.

자주 묻는 질문

“집계 파이프라인 최적화 팁” 강의는 무료인가요?

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

“집계 파이프라인 최적화 팁”에서 뭘 배우나요?

학습자는 $match와 $project를 앞부분으로 이동하고, $match 전에 $unwind를 사용하지 않으며, 대규모 정렬에는 allowDiskUse를 사용하도록 집계 파이프라인을 재구성합니다. 브라우저에서 직접 실행하는 실습 코드로 MongoDB Academy을(를) 배우며, 24/7 AI 튜터가 강의를 진행하면서 질문에 답변해줍니다.

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

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

“집계 파이프라인 최적화 팁” 강의는 얼마나 걸리나요?

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

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

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

이 강의의 모든 강의

  1. 데이터베이스 프로파일러와 느린 쿼리 로그
  2. 복합 인덱스 접두사 규칙과 ESR 원칙
  3. 인덱스 교차와 복합 인덱스 비교
  4. 집계 파이프라인 최적화 팁
← MongoDB Academy(으)로 돌아가기