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.

Similar Reads

Understanding the $first Operator

The $first operator retrieves the first document from a group of documents based on a specified sorting order. This allows us to extract specific data points or summaries from grouped data sets. It is commonly used in conjunction with the $group stage to group documents by a specific field or expression and then extract the first document from each group. This is useful for creating summaries or extracting key information from grouped data. The $first operator is used within the $group stage of an aggregation pipeline. It takes the form { $first: "$fieldName" }, where "fieldName" is the name of the field whose value we want to extract from the first document in each group....

Example of MongoDB Aggregation $first Operator

Suppose we We want to find the oldest student in each grade. Here’s how we can use the $first operator to achieve this:...

Handling Multiple Fields

The $first operator can be used with multiple fields to retrieve the first document containing specific values....

Conclusion

Overall, The $first operator in MongoDB’s aggregation framework is a valuable tool for retrieving the first document in each group based on a specified sorting order. Whether finding the oldest student in each grade or extracting other relevant information from grouped data, $first provides a straightforward and efficient way to accomplish these tasks....