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.

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.

Syntax:

The basic syntax of the $first operator within a $group stage is as follows:

{
$group: {
_id: <expression>,
firstField: { $first: "$fieldName" }
}
}

Explanation:

  • _id: The field or expression used to group documents.
  • firstField: The output field that will contain the first document from each group.
  • $first: “$fieldName”: The $first operator indicates that the value of the specified field (fieldName) from the first document in each group should be returned.

Let’s set up an Environment:

To understand MongoDB Aggregation $first Operator we need a collection and some documents on which we will perform various operations and queries. Here we will consider a collection called students which contains information in various documents are shown below.

([
... { "name": "Alice", "age": 18, "grade": 10 },
... { "name": "Bob", "age": 17, "grade": 10 },
... { "name": "Charlie", "age": 16, "grade": 11 },
... { "name": "David", "age": 18, "grade": 11 },
... { "name": "Eva", "age": 17, "grade": 12 },
... { "name": "Frank", "age": 16, "grade": 12 }
... ])

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:

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

Output:

[
{ "_id": 10, "oldestStudent": "Alice" },
{ "_id": 11, "oldestStudent": "Charlie" },
{ "_id": 12, "oldestStudent": "Eva" }
]

Explanation:

  • $group groups documents by the grade field.
  • $first: “$name” retrieves the value of the name field from the first document in each group, which corresponds to the oldest student in that grade.
  • This output shows the oldest student in each grade based on the first document encountered during grouping.

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.

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.

By understanding the syntax and usage of the $first operator, developers can leverage its capabilities to perform various data analysis tasks within MongoDB. Experimenting with different scenarios and datasets will further enhance your understanding and proficiency with this powerful aggregation operator.