![]() |
VOOZH | about |
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.
{
$group: {
_id: <expression>,
firstField: { $first: "$fieldName" }
}
}
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 }
... ])
db.students.aggregate([
{ $sort: { grade: 1, age: -1 } },
{
$group: {
_id: "$grade",
oldestStudent: { $first: "$name" }
}
}
])
Output:
[
{ "_id": 10, "oldestStudent": "Alex" },
{ "_id": 11, "oldestStudent": "Clevin" },
{ "_id": 12, "oldestStudent": "Eva" }
]
Find the first and last names of the oldest student in each grade.
db.students.aggregate([
{
$group: {
_id: "$grade",
oldestStudentFirst: { $first: "$name" },
oldestStudentLast: { $last: "$name" }
}
}
])
Output:
[
{ "_id": 10, "oldestStudentFirst": "Alex", "oldestStudentLast": "Ben" },
{ "_id": 11, "oldestStudentFirst": "Clevin", "oldestStudentLast": "David" },
{ "_id": 12, "oldestStudentFirst": "Eva", "oldestStudentLast": "Frank" }
]
Used $first to retrieve the first name and $last to retrieve the last name of the oldest student in each grade.