$push e $addToSet: creare array nei gruppi
I partecipanti raccoglieranno in array i valori dei documenti raggruppati ed elimineranno i duplicati con $addToSet.
$push e $addToSet: creare array nei gruppi è una lezione MongoDB Academy gratuita su CoddyKit. Questa è la lezione 2 di 4. Puoi leggere la lezione completa qui gratuitamente — poi esercitati direttamente nel browser con un editor di codice integrato e un tutor IA disponibile 24/7. Fa parte del percorso di apprendimento MongoDB Academy, e i tuoi progressi si sincronizzano tra il web e l'app CoddyKit. Il corso MongoDB Academy include 4 lezioni in totale.
Parti di questa lezione non sono ancora state tradotte e vengono mostrate in inglese.
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.
Impara JavaScript con un tutor IA — gratis
Scrivi ed esegui vero codice nel tuo browser, ricevi aiuto istantaneo da un tutor IA disponibile 24/7, e riprendi da dove hai lasciato sul web o nell'app.
- Corsi
- 30
- Lezioni
- 120
Domande Frequenti
La lezione «$push e $addToSet: creare array nei gruppi» è gratuita?
Sì — il testo completo di «$push e $addToSet: creare array nei gruppi» è gratuito qui sul web. Per esercitarvi in modo interattivo (un editor di codice integrato e un tutor IA 24/7) e sbloccare il resto del corso MongoDB Academy, passa a CoddyKit PRO. Il corso MongoDB Academy include 4 lezioni in totale.
Cosa imparerò in «$push e $addToSet: creare array nei gruppi»?
I partecipanti raccoglieranno in array i valori dei documenti raggruppati ed elimineranno i duplicati con $addToSet. Eserciti MongoDB Academy con codice pratico che esegui direttamente nel browser, e un tutor IA 24/7 risponde alle tue domande mentre lavori sulla lezione.
Ho bisogno di esperienza per iniziare MongoDB Academy?
Non è richiesta alcuna esperienza precedente. MongoDB Academy su CoddyKit è strutturato per principianti e studenti avanzati, quindi puoi iniziare da qui o dall'inizio e procedere al tuo ritmo. Questa è la lezione 2 di 4.
Quanto tempo richiede la lezione «$push e $addToSet: creare array nei gruppi»?
La maggior parte delle lezioni CoddyKit richiede circa 5–10 minuti. Ogni lezione è breve e interattiva, quindi fai progressi costanti e riprendi esattamente da dove hai lasciato su web e app.
Posso scrivere ed eseguire codice in questa lezione MongoDB Academy?
Sì. Ogni lezione MongoDB Academy include un editor di codice integrato, quindi scrivi ed esegui codice reale direttamente nel tuo browser e ricevi feedback istantaneo dall'IA — nessuna configurazione locale necessaria.
Tutte le lezioni di questo corso
- $sum, $avg, $min, $max: aggregazioni numeriche
- $push e $addToSet: creare array nei gruppi
- Accumulatori $first, $last e $top/$bottom
- Funzioni finestra con $setWindowFields