$push 和 $addToSet:在分组中构建数组
您将把分组文档中的值收集到数组中,并使用 $addToSet 去除重复值。
$push 和 $addToSet:在分组中构建数组 是 CoddyKit 上的免费 MongoDB Academy 课时。 这是第 2 节课,共 4 节。 你可以在下方免费阅读本课时的完整内容 — 然后在浏览器中使用内置代码编辑器和全天候 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:在分组中构建数组」的完整文本可在网页上免费阅读。要进行交互式练习(内置代码编辑器和全天候 AI 导师)并解锁 MongoDB Academy 课程的其余内容,请升级到 CoddyKit PRO。 MongoDB Academy 课程共包含 4 节课。
「$push 和 $addToSet:在分组中构建数组」这节课中我会学到什么?
您将把分组文档中的值收集到数组中,并使用 $addToSet 去除重复值。 你通过在浏览器中直接运行的动手代码来练习 MongoDB Academy,全天候 AI 导师会在你学习这节课的过程中回答你的问题。
学习 MongoDB Academy 需要有经验吗?
无需任何先前经验。CoddyKit 上的 MongoDB Academy 课程适合初学者到高级学习者,你可以从这里开始或从头开始,按照自己的节奏学习。 这是第 2 节课,共 4 节。
「$push 和 $addToSet:在分组中构建数组」课时需要多长时间?
大多数 CoddyKit 课程大约需要 5–10 分钟。每节课都很精短且互动,所以你能稳步进步,并在网页和应用中从离开的地方继续。
我能在这节 MongoDB Academy 课中编写并运行代码吗?
能。每节 MongoDB Academy 课都包含内置代码编辑器,你可以在浏览器中直接编写并运行真实代码,并获得即时 AI 反馈 — 无需本地设置。
此课程中的所有课时
- $sum、$avg、$min、$max:数值聚合
- $push 和 $addToSet:在分组中构建数组
- $first、$last 以及 $top/$bottom 累加器
- 使用 $setWindowFields 进行窗口函数计算