Example 1 — Sample Data
Imagine one player named Alice with four quiz scores, and one order with three products. We save them in players and orders.
db.players.insertOne({
_id: 1,
name: "Alice",
scores: [85, 92, 78, 95]
});
db.orders.insertOne({
_id: 1,
orderId: "A100",
items: [
{ name: "Keyboard", price: 80 },
{ name: "Cable", price: 10 },
{ name: "Mouse", price: 25 }
]
}); How the Data Is Stored in MongoDB
After the inserts, MongoDB keeps one document in each collection. Run find() to see them:
db.players.find()
db.orders.find() Read those documents like this:
| Field in MongoDB | Value | Plain English |
|---|---|---|
scores | [85, 92, 78, 95] | Quiz scores (unsorted) |
items | 3 product objects | Line items with name and price |
items[].price | 80, 10, 25 | Sort key for Example 3 |
Alice scores (as stored):
[85, 92, 78, 95]
After sortBy: -1 (highest first):
[95, 92, 85, 78]
Order items (as stored):
Keyboard $80 → Cable $10 → Mouse $25
After sortBy: { price: 1 } (cheapest first):
Cable $10 → Mouse $25 → Keyboard $80 How It Works
- Insert once.
insertOneadds Alice toplayersand the order toorders. - Arrays stay as written. Scores and items keep their original order until we sort them.
- find() shows the same shape. What you inserted is what you get back—ready for
$sortArraynext.

