Example 1 — Sample Data
Three products with multiple sale dates. Item abc has a clear earliest sale in January—perfect for checking $first.
db.sales.insertMany([
{ _id: 1, item: "abc", price: 10, quantity: 2,
date: ISODate("2014-01-01T08:00:00Z") },
{ _id: 2, item: "jkl", price: 20, quantity: 1,
date: ISODate("2014-02-03T09:00:00Z") },
{ _id: 3, item: "xyz", price: 5, quantity: 5,
date: ISODate("2014-02-03T09:05:00Z") },
{ _id: 4, item: "abc", price: 10, quantity: 10,
date: ISODate("2014-02-15T08:00:00Z") },
{ _id: 5, item: "xyz", price: 5, quantity: 10,
date: ISODate("2014-02-15T09:05:00Z") },
{ _id: 6, item: "xyz", price: 5, quantity: 5,
date: ISODate("2014-02-15T12:05:10Z") },
{ _id: 7, item: "xyz", price: 5, quantity: 10,
date: ISODate("2014-02-15T14:12:12Z") }
]); How the Data Is Stored in MongoDB
After the insert, MongoDB keeps 7 documents in sales. Run find() to see them:
db.sales.find().sort({ _id: 1 }) Read each document like this:
| Field in MongoDB | Meaning | Example |
|---|---|---|
_id | Sale id | 1 |
item | Product code | "abc" |
price | Unit price | 10 |
quantity | How many sold | 2 |
date | When the sale happened | 2014-01-01 |
Sales by item (earliest first after $sort):
abc: Jan 1, then Feb 15
jkl: Feb 3
xyz: Feb 3, then three on Feb 15
Next: $first keeps the earliest sale date per item. How It Works
- Insert once.
insertManyadds seven sale documents tosales. - MongoDB stores fields as written. Each sale has
item,price,quantity, anddate. - find() shows the same shape. What you inserted is what you get back—ready for
$firstafter a$sort.

