Learning MongoDB

0% completed

Previous
Next
mongodb aggregation $first

The $first operator in MongoDB's aggregation framework is used to return the first element in an array or the first document within a group. It is particularly useful when you want to retrieve the earliest or first occurring element based on a specified ordering.

Syntax

{ $group: { _id: <expression>, firstField: { $first: <expression> } } }
  • $group: The operator used to specify the grouping stage.
  • _id: The expression to group by.
  • firstField: The field to store the first element.
  • $first: The operator to get the first element in the group.

Example Setup

First, let's insert some documents into the sales collection to work with:

db.sales.insertMany([ { sale_id: 1, item: "apple", quantity: 10, date: new Date("2023-01-01") }, { sale_id: 2, item: "banana", quantity: 5, date: new Date("2023-01-02") }, { sale_id: 3, item: "orange", quantity: 8, date: new Date("2023-01-03") }, { sale_id: 4, item: "apple", quantity: 15, date: new Date("2023-01-04") }, { sale_id: 5, item: "banana", quantity: 7, date: new Date("2023-01-05") } ])

Example 1: Basic Usage of $first

Retrieve the first sale for each item.

Pipeline:

db.sales.aggregate([ { $sort: { date: 1 } }, { $group: { _id: "$item", firstSale: { $first: "$$ROOT" } } } ])

Explanation:

  • $sort: Sorts the documents by the date field in ascending order.
  • group: Groups the documents by the item field. The $first operator retrieves the first document in each group, which is the earliest sale due to the prior sorting.

This command results in documents like:

{ "_id": "apple", "firstSale": { "sale_id": 1, "item": "apple", "quantity": 10, "date": "2023-01-01T00:00:00Z" } }

Example 2: Using $first with a Different Field

Retrieve the first quantity sold for each item.

Pipeline:

db.sales.aggregate([ { $sort: { date: 1 } }, { $group: { _id: "$item", firstQuantity: { $first: "$quantity" } } } ])

Explanation:

  • $sort: Sorts the documents by the date field in ascending order.
  • group: Groups the documents by the item field. The $first operator retrieves the first quantity value in each group, which corresponds to the earliest sale due to the prior sorting.

This command results in documents like:

{ "_id": "apple", "firstQuantity": 10 }

Example 3: Combining $first with Other Aggregation Operations

Retrieve the first sale and the total quantity sold for each item.

Pipeline:

db.sales.aggregate([ { $sort: { date: 1 } }, { $group: { _id: "$item", firstSale: { $first: "$$ROOT" }, totalQuantity: { $sum: "$quantity" } } } ])

Explanation:

  • $sort: Sorts the documents by the date field in ascending order.
  • group: Groups the documents by the item field. The $first operator retrieves the first document in each group, and the $sum operator calculates the total quantity sold for each item.

This command results in documents like:

{ "_id": "apple", "firstSale": { "sale_id": 1, "item": "apple", "quantity": 10, "date": "2023-01-01T00:00:00Z" }, "totalQuantity": 25 }

Use Cases

  1. Data Retrieval: Retrieve the first occurrence of an event, such as the first sale of an item.
  2. Reporting: Generate reports that require the earliest record, such as the first transaction of each day.
  3. Data Processing: Use in conjunction with grouping to get the first record based on a specific order, such as the first log entry for each user.

The $first operator is a valuable tool in MongoDB's aggregation framework for retrieving the first element in a group. By understanding how to use the $first operator effectively, you can perform detailed data retrieval, generate reports, and process data in meaningful ways.

.....

.....

.....

Like the course? Get enrolled and start learning!
Previous
Next