0
0
MongodbHow-ToBeginner · 3 min read

How to Use $first in Aggregation in MongoDB: Syntax and Examples

In MongoDB aggregation, $first returns the first value from the documents in each group or pipeline stage. It is commonly used inside a $group stage to get the first document's field value based on the input order.
📐

Syntax

The $first operator is used inside the $group stage of an aggregation pipeline. It returns the first value for a specified field from the documents in each group.

  • { $first: <expression> }: Returns the first value of the expression in the group.
  • <expression> can be a field path like $fieldName.
json
{
  $group: {
    _id: "$groupField",
    firstValue: { $first: "$fieldName" }
  }
}
💻

Example

This example groups documents by the "category" field and returns the first "item" value found in each category.

mongodb
db.inventory.aggregate([
  {
    $group: {
      _id: "$category",
      firstItem: { $first: "$item" }
    }
  }
])
Output
[ { "_id" : "fruit", "firstItem" : "apple" }, { "_id" : "vegetable", "firstItem" : "carrot" } ]
⚠️

Common Pitfalls

Common mistakes when using $first include:

  • Expecting $first to return the first value sorted by a field. It returns the first document in the input order, so sorting must be done before grouping.
  • Using $first outside of a $group stage, which will cause errors.
mongodb
/* Wrong: $first without sorting */
db.inventory.aggregate([
  {
    $group: {
      _id: "$category",
      firstItem: { $first: "$item" }
    }
  }
])

/* Right: Sort first, then group */
db.inventory.aggregate([
  { $sort: { date: 1 } },
  {
    $group: {
      _id: "$category",
      firstItem: { $first: "$item" }
    }
  }
])
📊

Quick Reference

OperatorDescriptionUsage Context
$firstReturns the first value from documents in a groupInside $group stage
$sortSorts documents to control which is firstBefore $group stage
$lastReturns the last value from documents in a groupInside $group stage

Key Takeaways

Use $first inside $group to get the first value of a field per group.
Sort documents before grouping to control which document is considered first.
$first returns the first document in the input order, not sorted automatically.
Using $first outside $group causes errors.
Combine $sort and $group with $first for predictable results.