MongoDB Aggregation $first Operator (original) (raw)

Last Updated : 5 May, 2026

The $first operator in MongoDB returns the first document’s field value from each group in an aggregation pipeline, based on the current sort order.

Syntax

{
$group: {
_id: ,
firstField: { first:"first: "first:"fieldName" }
}
}

Example of MongoDB Aggregation $first Operator

Consider a collection called students which contains information in various documents are shown below.

([
... { "name": "Alex", "age": 18, "grade": 10 },
... { "name": "Ben", "age": 17, "grade": 10 },
... { "name": "Clevin", "age": 16, "grade": 11 },
... { "name": "David", "age": 18, "grade": 11 },
... { "name": "Eva", "age": 17, "grade": 12 },
... { "name": "Frank", "age": 16, "grade": 12 }
... ])

Example 1: Find the oldest student in each grade after sorting

db.students.aggregate([
{ $sort: { grade: 1, age: -1 } },
{
$group: {
_id: "$grade",
oldestStudent: { first:"first: "first:"name" }
}
}
])

**Output:

[
{ "_id": 10, "oldestStudent": "Alex" },
{ "_id": 11, "oldestStudent": "Clevin" },
{ "_id": 12, "oldestStudent": "Eva" }
]

Example 2: Handling Multiple Fields

Find the first and last names of the oldest student in each grade.

db.students.aggregate([
{
$group: {
_id: "$grade",
oldestStudentFirst: { first:"first: "first:"name" },
oldestStudentLast: { last:"last: "last:"name" }
}
}
])

**Output:

[
{ "_id": 10, "oldestStudentFirst": "Alex", "oldestStudentLast": "Ben" },
{ "_id": 11, "oldestStudentFirst": "Clevin", "oldestStudentLast": "David" },
{ "_id": 12, "oldestStudentFirst": "Eva", "oldestStudentLast": "Frank" }
]

Used firsttoretrievethefirstnameandfirst to retrieve the first name and firsttoretrievethefirstnameandlast to retrieve the last name of the oldest student in each grade.