Example 1 — Sample Data
Imagine four sales in a sales collection. Each document has an item, a date, and a price.
db.sales.insertMany([
{ item: "abc", price: 10, date: ISODate("2014-01-01T08:00:00Z") },
{ item: "abc", price: 12, date: ISODate("2014-02-15T08:00:00Z") },
{ item: "xyz", price: 5, date: ISODate("2014-02-03T09:00:00Z") },
{ item: "xyz", price: 8, date: ISODate("2014-02-15T14:00:00Z") }
]); How the Data Is Stored in MongoDB
After the insert, MongoDB keeps 4 documents in sales. Run find() to see them:
db.sales.find() Read each document like this:
| Field in MongoDB | Meaning | Example |
|---|---|---|
item | Product code | "abc" |
price | Sale price | 12 |
date | When the sale happened | 2014-02-15 |
abc sales: Jan 1 (price 10), Feb 15 (price 12)
xyz sales: Feb 3 (price 5), Feb 15 (price 8)
Next: $last keeps the latest sale per item (after $sort). How It Works
- Insert once. The sample command adds 4 documents to
sales. - MongoDB stores fields as written. Each document keeps the same field names and values you inserted.
- find() shows the same shape. What you inserted is what you get back—ready for
$lastin the next examples.
After sorting by date ascending, the last sale for each item is on 2014-02-15.

