0% completed
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.
{ $group: { _id: <expression>, firstField: { $first: <expression> } } }
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") } ])
Retrieve the first sale for each item.
Pipeline:
db.sales.aggregate([ { $sort: { date: 1 } }, { $group: { _id: "$item", firstSale: { $first: "$$ROOT" } } } ])
Explanation:
date
field in ascending order.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" } }
Retrieve the first quantity sold for each item.
Pipeline:
db.sales.aggregate([ { $sort: { date: 1 } }, { $group: { _id: "$item", firstQuantity: { $first: "$quantity" } } } ])
Explanation:
date
field in ascending order.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 }
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:
date
field in ascending order.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 }
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.
.....
.....
.....