ตัวรวม $first, $last และ $top/$bottom
ผู้เรียนจะเลือกเอกสารแรกหรือเอกสารสุดท้ายของแต่ละกลุ่ม และใช้ตัวรวมรุ่นใหม่อย่าง $top และ $bottom เพื่อเลือกตามคีย์การเรียงลำดับ
ตัวรวม $first, $last และ $top/$bottom เป็นบทเรียน MongoDB Academy ฟรีบน CoddyKit นี่คือบทเรียนที่ 3 จากทั้งหมด 4 บทเรียน คุณสามารถอ่านบทเรียนทั้งหมดด้านล่างฟรี — จากนั้นลองปฏิบัติด้วยตัวคุณเองในเบราว์เซอร์พร้อมตัวแก้ไขโค้ดในตัวและติวเตอร์ AI ตลอด 24/7 บทเรียนนี้เป็นส่วนหนึ่งของเส้นทางการเรียน MongoDB Academy และความก้าวหน้าของคุณจะซิงค์ข้ามเว็บและแอป CoddyKit คอร์ส MongoDB Academy มีบทเรียนทั้งหมด 4 บทเรียน
บางส่วนของบทเรียนนี้ยังไม่ได้รับการแปล และแสดงเป็นภาษาอังกฤษ
Picking One Document Per Group
Sometimes aggregation needs to select a single representative document from each group rather than computing a numeric aggregate. MongoDB provides several accumulators for this: $first, $last, and the newer $top and $bottom accumulators. Each has different semantics for determining which document is selected, and choosing the right one affects both correctness and performance.
$first: Taking the Earliest Document Value
$first returns the value from the first document encountered in the group. Since MongoDB does not guarantee document processing order within a $group unless you sort first, $first is meaningful only when you place a $sort stage immediately before the $group. This two-stage pattern—sort then group—is the standard way to reliably pick the earliest or highest-priority item per group.
db.orders.aggregate([
// Sort by date ascending so $first gets the oldest order
{ $sort: { createdAt: 1 } },
{
$group: {
_id: '$customerId',
firstOrderDate: { $first: '$createdAt' },
firstOrderAmount: { $first: '$amount' },
firstOrderId: { $first: '$_id' }
}
}
])$last: Taking the Latest Document Value
$last returns the value from the last document encountered in the group. Again, this is meaningful only when combined with a preceding $sort. Sort ascending and use $last to get the most recent value per group. Sort descending and use $first to achieve the same result. The most common use case is finding each user's or customer's most recent activity.
db.loginEvents.aggregate([
// Sort ascending: $last will be the most recent event
{ $sort: { timestamp: 1 } },
{
$group: {
_id: '$userId',
lastLoginTime: { $last: '$timestamp' },
lastLoginIp: { $last: '$ipAddress' },
totalLogins: { $sum: 1 }
}
}
])Performance Cost of Sort Before Group
The pattern of $sort before $group has an important performance implication: it prevents MongoDB from pushing the $group in front of the $sort during pipeline optimization. If the collection is large and you have an index on the sort field, MongoDB can use it for the sort phase but still must sort all documents before grouping. For very large collections, this can be expensive. The $top and $bottom accumulators were introduced partly to address this limitation.
// Potentially expensive on large collections:
// MongoDB must sort ALL documents before grouping
db.events.aggregate([
{ $sort: { timestamp: -1 } }, // sorts entire collection
{
$group: {
_id: '$userId',
latestEvent: { $first: '$eventType' }
}
}
])$top: Pick by Sort Key Within Group
Introduced in MongoDB 5.2, $top lets you pick the top document within each group according to a sort specification—without a separate $sort stage. You specify a sortBy expression and an output expression directly inside the accumulator. MongoDB evaluates the sort per group, which can be more efficient than sorting the entire collection first.
db.orders.aggregate([
{
$group: {
_id: '$customerId',
mostRecentOrder: {
$top: {
sortBy: { createdAt: -1 }, // highest date first
output: {
orderId: '$_id',
amount: '$amount',
date: '$createdAt'
}
}
}
}
}
])$bottom: Pick the Last by Sort Key
$bottom is the complement to $top—it returns the document that would appear last after sorting by the given key within each group. Use $bottom with sortBy: { timestamp: 1 } to get the earliest event per group, or use $top with the opposite sort direction—both approaches are equivalent. Choose whichever expresses your intent more clearly.
db.gameScores.aggregate([
{
$group: {
_id: '$playerId',
highestScore: {
$top: {
sortBy: { score: -1 },
output: { score: '$score', level: '$level', date: '$date' }
}
},
lowestScore: {
$bottom: {
sortBy: { score: -1 },
output: { score: '$score', level: '$level', date: '$date' }
}
}
}
}
])$topN and $bottomN: Picking Multiple Items
MongoDB also provides $topN and $bottomN accumulators that return an array of the top or bottom N documents per group according to a sort key. This is useful for leaderboard-style queries where you want the top 3 scores per level or the 5 most recent orders per customer, all computed in a single $group stage.
db.scores.aggregate([
{
$group: {
_id: '$gameId',
top3Players: {
$topN: {
n: 3,
sortBy: { score: -1 },
output: { playerId: '$playerId', score: '$score' }
}
}
}
}
])Choosing Between $first/$last and $top/$bottom
Use $first/$last when you are already sorting the pipeline for other reasons and want a simple, familiar API. Use $top/$bottom when you only need the selection behavior and want to avoid the cost of a full collection sort before $group. In practice, $top/$bottom with appropriate indexes can be significantly faster for large collections because MongoDB may be able to optimize the per-group selection more efficiently.
// Prefer $top when no prior $sort is needed for other stages:
db.orders.aggregate([
{
$group: {
_id: '$region',
latestOrder: {
$top: { sortBy: { date: -1 }, output: { amount: '$amount', date: '$date' } }
}
}
}
]);
// Use $first when you are already sorting for other accumulators:
db.orders.aggregate([
{ $sort: { date: -1 } },
{
$group: {
_id: '$region',
latestDate: { $first: '$date' },
latestAmount: { $first: '$amount' },
allAmounts: { $push: '$amount' } // also needs sorted input
}
}
])Practical Use Case: Latest Price Per Product
A classic real-world use case is maintaining a price history collection and querying the latest effective price for each product. Using $top with sort by date descending makes this query concise and efficient. The result is one document per product containing its current price without needing a separate 'current price' collection.
db.priceHistory.aggregate([
{
$group: {
_id: '$productId',
currentPrice: {
$top: {
sortBy: { effectiveDate: -1 },
output: {
price: '$price',
currency: '$currency',
effectiveDate: '$effectiveDate'
}
}
}
}
}
])Combining Accumulators in One $group
You can freely combine $first, $last, $top, $bottom, $sum, $avg, and $push in a single $group stage. Each accumulator operates independently on the documents in the group. This lets you compute summary statistics alongside picking representative documents in one efficient aggregation stage, avoiding multiple passes over the data.
db.transactions.aggregate([
{ $sort: { timestamp: 1 } },
{
$group: {
_id: '$accountId',
firstTransaction: { $first: '$timestamp' },
lastTransaction: { $last: '$timestamp' },
transactionCount: { $sum: 1 },
totalVolume: { $sum: '$amount' },
avgTransaction: { $avg: '$amount' },
largestTransaction: { $max: '$amount' }
}
}
])Version Compatibility Notes
$first and $last have been available since early MongoDB versions. The $top and $bottom accumulators were introduced in MongoDB 5.2, and $topN/$bottomN also became available around that time. If you are using an older MongoDB version (pre-5.2), fall back to the $sort then $first/$last pattern. Check your Atlas cluster version or self-hosted version before using newer operators.
Quick Check
Test your understanding of MongoDB & NoSQL Databases concepts from this lesson.
Lesson Recap
In this lesson you learned: $first/$last pick values from the first/last document in a group (requires prior $sort), $top/$bottom (MongoDB 5.2+) pick by sort key within the group without a separate $sort stage, and $topN/$bottomN return arrays of the top or bottom N items per group. Next up we explore window functions with $setWindowFields for running totals and moving averages.
เรียนรู้ JavaScript ด้วย AI tutor — ฟรี
เขียนและเรียกใช้โค้ดจริงในเบราว์เซอร์ของคุณ รับความช่วยเหลือทันทีจาก AI tutor 24/7 และเรียนรู้ต่อจากที่คุณหยุดบนเว็บหรือในแอป
- คอร์ส
- 30
- บทเรียน
- 120
คำถามที่พบบ่อย
บทเรียน “ตัวรวม $first, $last และ $top/$bottom” ฟรีหรือไม่
ใช่ — ข้อความเต็มของ “ตัวรวม $first, $last และ $top/$bottom” ฟรีให้อ่านที่นี่บนเว็บ เพื่อปฏิบัติแบบโต้ตอบ (ตัวแก้ไขโค้ดในตัวและติวเตอร์ AI ตลอด 24/7) และปลดล็อคส่วนที่เหลือของคอร์ส MongoDB Academy ให้อัปเกรดเป็น CoddyKit PRO คอร์ส MongoDB Academy มีบทเรียนทั้งหมด 4 บทเรียน
คุณจะเรียนรู้อะไรในบทเรียน “ตัวรวม $first, $last และ $top/$bottom”
ผู้เรียนจะเลือกเอกสารแรกหรือเอกสารสุดท้ายของแต่ละกลุ่ม และใช้ตัวรวมรุ่นใหม่อย่าง $top และ $bottom เพื่อเลือกตามคีย์การเรียงลำดับ คุณปฏิบัติ MongoDB Academy ด้วยโค้ดที่ใช้งานได้จริงที่คุณเรียกใช้โดยตรงในเบราว์เซอร์ และติวเตอร์ AI ตลอด 24/7 ตอบคำถามของคุณขณะที่คุณไปผ่านบทเรียน
คุณต้องมีประสบการณ์ก่อนที่จะเริ่มเรียน MongoDB Academy หรือไม่
ไม่จำเป็นต้องมีประสบการณ์มาก่อน MongoDB Academy บน CoddyKit ออกแบบมาสำหรับผู้เริ่มต้นไปจนถึงผู้เรียนขั้นสูง คุณสามารถเริ่มต้นที่นี่หรือเริ่มจากตัวแรกและเรียนด้วยความเร็วของคุณเอง นี่คือบทเรียนที่ 3 จากทั้งหมด 4 บทเรียน
บทเรียน “ตัวรวม $first, $last และ $top/$bottom” ใช้เวลานานแค่ไหน
บทเรียน CoddyKit ส่วนใหญ่ใช้เวลาประมาณ 5–10 นาที แต่ละบทเรียนจึงสั้นและเป็นแบบโต้ตอบ คุณสามารถก้าวหน้าอย่างต่อเนื่องและกลับมาเรียนต่อจากตรงที่เพิ่งหยุดบนเว็บและแอปได้เลย
ฉันเขียนและรันโค้ดในบทเรียน MongoDB Academy นี้ได้ไหม
ได้ บทเรียน MongoDB Academy ทุกบทมีตัวแก้ไขโค้ดในตัว คุณจึงเขียนและรันโค้ดจริงได้เลยในเบราว์เซอร์ และได้รับข้อเสนอแนะจาก AI ในทันที — ไม่ต้องติดตั้งในเครื่องของคุณ
บทเรียนทั้งหมดในหลักสูตรนี้
- $sum, $avg, $min, $max: การรวมข้อมูลเชิงตัวเลข
- $push และ $addToSet: การสร้างอาร์เรย์ในกลุ่ม
- ตัวรวม $first, $last และ $top/$bottom
- ฟังก์ชันหน้าต่างด้วย $setWindowFields