$push와 $addToSet: 그룹에서 배열 만들기
학습자는 그룹화된 문서의 값을 배열로 모으고 $addToSet으로 중복을 제거합니다.
$push와 $addToSet: 그룹에서 배열 만들기은(는) CoddyKit의 무료 MongoDB Academy 강의입니다. 이것은 4개 중 2번째 강의입니다. 아래에서 전체 강의를 무료로 읽을 수 있으며, 내장 코드 에디터와 24/7 AI 튜터와 함께 브라우저에서 직접 실습할 수 있습니다. 이 강의는 MongoDB Academy 학습 경로의 일부이며, 진행 상황이 웹과 CoddyKit 앱에 동기화됩니다. MongoDB Academy 강의에는 총 4개의 강의가 포함되어 있습니다.
이 강의의 일부는 아직 번역되지 않았으며 영어로 표시됩니다.
Collecting Values Into Arrays
When grouping documents, sometimes you want to collect individual field values into an array rather than compute a numeric aggregate. MongoDB provides two accumulators for this: $push and $addToSet. Both build an array result from grouped documents, but they differ in how they handle duplicate values. These accumulators are essential for producing denormalized or grouped results.
$push: Collecting All Values
$push appends the specified expression value to an array for every document in the group. It preserves duplicates—if multiple documents share the same value, that value will appear multiple times in the resulting array. The order of elements in the array corresponds to the order documents were processed, which may vary unless you sort before grouping.
db.orders.aggregate([
{
$group: {
_id: '$customerId',
// Collect all product IDs ordered by this customer
orderedProducts: { $push: '$productId' },
orderDates: { $push: '$createdAt' }
}
}
])$addToSet: Collecting Unique Values
$addToSet works like $push except it deduplicates—each unique value is added to the array only once. The resulting array contains no repeated elements, similar to a mathematical set. The order of elements in the output is not guaranteed when using $addToSet, so do not depend on element ordering. Use it when you need a distinct list of values per group.
db.logs.aggregate([
{
$group: {
_id: {
year: { $year: '$timestamp' },
month: { $month: '$timestamp' }
},
// Unique users who logged in this month
uniqueUsers: { $addToSet: '$userId' },
// Every event type including duplicates
allEvents: { $push: '$eventType' }
}
}
])Pushing Embedded Objects
You can $push entire subdocuments or computed objects, not just scalar values. By constructing an object expression, you can collect multiple fields from each document into a structured array element. This is useful for creating summary records that embed the details of each contributing document.
db.orders.aggregate([
{
$group: {
_id: '$customerId',
orderHistory: {
$push: {
orderId: '$_id',
amount: '$amount',
status: '$status',
date: '$createdAt'
}
}
}
}
])Combining $push With $sort
Because the order of elements in a $push array depends on document processing order, you should add a $sort stage before $group when the order of the collected array matters. For example, to collect orders in chronological order within each customer group, sort by date first. Note that sorting before $group prevents MongoDB from using many index optimizations, so consider the performance trade-off.
db.orders.aggregate([
// Sort by date first so $push produces ordered arrays
{ $sort: { createdAt: 1 } },
{
$group: {
_id: '$customerId',
ordersInChronologicalOrder: {
$push: {
orderId: '$_id',
date: '$createdAt',
amount: '$amount'
}
}
}
}
])Document Size Limits and Array Growth
MongoDB documents have a 16 MB size limit. When using $push in a $group stage, the resulting document could exceed this limit if a group contains many documents or if each pushed value is large. This is a runtime error, not a schema error. Mitigate this by filtering data before grouping, projecting only needed fields into $push, or using $limit combined with $sort to push only top-N items.
// Safe pattern: project only needed fields before pushing
db.events.aggregate([
{ $match: { year: 2024 } },
{
$project: {
userId: 1,
eventType: 1 // exclude large 'payload' field
}
},
{
$group: {
_id: '$userId',
events: { $push: '$eventType' }
}
}
])Using $addToSet for Unique Tag Collections
A classic use case for $addToSet is aggregating unique tags or categories across documents in a group. For example, finding all unique skill tags across all job postings from each company, or all unique product categories purchased by each customer. The deduplication happens entirely server-side without requiring application-level filtering.
db.jobPostings.aggregate([
{
$group: {
_id: '$companyId',
uniqueSkills: { $addToSet: '$requiredSkills' },
totalPostings: { $sum: 1 }
}
},
{ $sort: { totalPostings: -1 } }
])Checking Array Size With $size in $project
After collecting values with $push or $addToSet, you often want to know how many items ended up in the array. Use $size in a subsequent $project or $addFields stage to compute the array length. You can also filter groups by array size using $match with $expr and $size.
db.orders.aggregate([
{
$group: {
_id: '$customerId',
products: { $addToSet: '$productId' }
}
},
{
$addFields: {
uniqueProductCount: { $size: '$products' }
}
},
// Only customers who bought 3 or more unique products
{ $match: { uniqueProductCount: { $gte: 3 } } }
])Unwinding After Grouping
Sometimes you need to reverse a $push—take the grouped array and expand it back into individual documents for further processing. The $unwind stage does exactly this. A common pattern is: $group with $push to consolidate → $project to transform → $unwind to expand → further $group or $match to refine results.
db.orders.aggregate([
{ $group: { _id: '$customerId', products: { $push: '$productId' } } },
// Expand back into per-product documents
{ $unwind: '$products' },
// Now further filter or group by product
{
$group: {
_id: '$products',
customerCount: { $sum: 1 }
}
},
{ $sort: { customerCount: -1 } }
])Real-World Pattern: User Activity Summary
A common production pattern is building a user activity summary document by grouping log events. Using $push and $addToSet together, you can generate a document that contains all event timestamps (ordered array via $push), all unique pages visited (deduped via $addToSet), and a total event count—all in one aggregation pass.
db.pageViews.aggregate([
{ $sort: { timestamp: 1 } },
{
$group: {
_id: '$userId',
visitTimestamps: { $push: '$timestamp' },
uniquePages: { $addToSet: '$page' },
totalVisits: { $sum: 1 }
}
},
{
$addFields: {
uniquePageCount: { $size: '$uniquePages' }
}
}
])$push vs $addToSet Comparison
To choose between $push and $addToSet, ask: do duplicates matter? Use $push when you need all values including repeats (e.g., event log, purchase history). Use $addToSet when you need only distinct values (e.g., unique tags, distinct pages visited). Remember that $addToSet does not guarantee any particular order of elements in the resulting array, while $push preserves insertion order relative to the pipeline input.
// $push — all values, order preserved
{ $push: '$tag' } // ['mongodb', 'nosql', 'mongodb', 'database']
// $addToSet — unique values only, order not guaranteed
{ $addToSet: '$tag' } // ['mongodb', 'database', 'nosql']Quick Check
Test your understanding of MongoDB & NoSQL Databases concepts from this lesson.
Lesson Recap
In this lesson you learned: $push collects all values including duplicates into an array, $addToSet collects only unique values with no guaranteed order, and both can push complex subdocuments and must respect the 16 MB document size limit. Next up we explore $first, $last, and the $top/$bottom accumulators for picking single documents per group.
자주 묻는 질문
“$push와 $addToSet: 그룹에서 배열 만들기” 강의는 무료인가요?
네 — “$push와 $addToSet: 그룹에서 배열 만들기” 전체 내용을 이 웹사이트에서 무료로 읽을 수 있습니다. 인터랙티브하게 실습하려면(내장 코드 에디터와 24/7 AI 튜터), CoddyKit PRO로 업그레이드하면 MongoDB Academy 강의 전체를 잠금 해제할 수 있습니다. MongoDB Academy 강의에는 총 4개의 강의가 포함되어 있습니다.
“$push와 $addToSet: 그룹에서 배열 만들기”에서 뭘 배우나요?
학습자는 그룹화된 문서의 값을 배열로 모으고 $addToSet으로 중복을 제거합니다. 브라우저에서 직접 실행하는 실습 코드로 MongoDB Academy을(를) 배우며, 24/7 AI 튜터가 강의를 진행하면서 질문에 답변해줍니다.
MongoDB Academy을(를) 시작하는 데 경험이 필요한가요?
사전 경험은 필요하지 않습니다. CoddyKit의 MongoDB Academy은(는) 초급자부터 고급 학습자까지를 위해 구성되어 있으므로, 여기서 시작하거나 처음부터 시작할 수 있으며 자신의 속도대로 진행할 수 있습니다. 이것은 4개 중 2번째 강의입니다.
“$push와 $addToSet: 그룹에서 배열 만들기” 강의는 얼마나 걸리나요?
대부분의 CoddyKit 강의는 약 5~10분이 소요됩니다. 각 강의는 간결하고 인터랙티브하여 꾸준한 진행이 가능하며, 웹과 앱에서 중단한 부분부터 바로 시작할 수 있습니다.
이 MongoDB Academy 강의에서 코드를 작성하고 실행할 수 있나요?
네. 모든 MongoDB Academy 강의에는 내장 코드 에디터가 포함되어 있으므로, 브라우저에서 바로 실제 코드를 작성하고 실행한 후 즉시 AI 피드백을 받을 수 있습니다 — 로컬 설정이 필요 없습니다.
이 강의의 모든 강의
- $sum, $avg, $min, $max: 숫자 집계
- $push와 $addToSet: 그룹에서 배열 만들기
- $first, $last 및 $top/$bottom 누산기
- $setWindowFields를 사용한 윈도 함수