Handling Multiple Fields
The $first operator can be used with multiple fields to retrieve the first document containing specific values.
Example:
Suppose we want to find the first and last names of the oldest student in each grade. We can use the $first operator multiple times within the $group stage.
db.students.aggregate([
{
$group: {
_id: "$grade",
oldestStudentFirst: { $first: "$name" },
oldestStudentLast: { $last: "$name" }
}
}
])
Output:
[
{ "_id": 10, "oldestStudentFirst": "Alice", "oldestStudentLast": "Bob" },
{ "_id": 11, "oldestStudentFirst": "Charlie", "oldestStudentLast": "David" },
{ "_id": 12, "oldestStudentFirst": "Eva", "oldestStudentLast": "Frank" }
]
Explanation: In this example, we use $first to retrieve the first name and $last to retrieve the last name of the oldest student in each grade.
MongoDB Aggregation $first Operator
MongoDB’s aggregation framework offers a rich set of operators for data manipulation and analysis. One such operator is $first, which retrieves the first document from a group of documents.
In this article, we will learn about the $first operator in MongoDB aggregation by covering its concepts and usage with beginner-friendly examples.