Introduction to MongoDB $first Operator

The $first operator is an aggregation operator in MongoDB that is used to retrieve the value of a specified field from the first document in a group. This operator is commonly used in data processing for statistical analysis.

Syntax

The syntax for using the $first operator in a MongoDB aggregation pipeline is as follows:

{
  $first: "<field>"
}

Here, <field> represents the name of the field to retrieve.

Use Cases

  • The $first operator is used to retrieve the value of a specified field from the first document in a group.
  • For sorted data sets, the $first operator can be used to retrieve the value of the first document in a group.

Examples

Here are some examples of the $first operator:

Sample Data

Consider a collection that stores students’ exam scores, including their names, scores, and subjects, as shown below:

{ name: "Alice", score: 85, subject: "math" }
{ name: "Alice", score: 90, subject: "history" }
{ name: "Bob", score: 80, subject: "math" }
{ name: "Bob", score: 70, subject: "history" }
{ name: "Charlie", score: 95, subject: "math" }
{ name: "Charlie", score: 75, subject: "history" }

Retrieving the first subject score for each student

To retrieve the first subject score for each student, you can use the following aggregation pipeline:

db.scores.aggregate([
  { $sort: { name: 1, subject: 1 } },
  { $group: { _id: "$name", firstScore: { $first: "$score" } } }
])

After executing this aggregation pipeline, the following results will be returned:

{ "_id" : "Alice", "firstScore" : 85 }
{ "_id" : "Bob", "firstScore" : 80 }
{ "_id" : "Charlie", "firstScore" : 95 }

Retrieving the first student score for each subject

To retrieve the first student score for each subject, you can use the following aggregation pipeline:

db.scores.aggregate([
  { $sort: { subject: 1, name: 1 } },
  { $group: { _id: "$subject", firstScore: { $first: "$score" } } }
])

After executing this aggregation pipeline, the following results will be returned:

{ "_id" : "history", "firstScore" : 70 }
{ "_id" : "math", "firstScore" : 80 }

Conclusion

The MongoDB $first operator can be used in an aggregation pipeline to retrieve the value of the first document in a group.