Typorithm · easy

$project & $sort

mongo-project-sortmongodbreshapecomputedordering
Saved on this device
Full lesson · 8 learning steps Open any exercise for focused practice
1

Step 1 of 8 · intro card

Learn $project & $sort

0%

Aggregation

$project reshapes documents — picking fields and adding computed ones like revenue from price and qty — then $sort orders the results and $limit takes the top N.

$project controls the output shape: include fields with 1, drop them with 0, and synthesize new ones from expressions.

Expression operators such as $multiply, $add, and $concat let a computed field like revenue derive from other fields.

$sort then orders the stream (-1 descending, 1 ascending), and $limit after it yields a clean top-N result.

01

$project includes (1), excludes (0), and computes fields.

02

$multiply and friends build computed values.

03

$sort orders; $limit takes the top N.

db.orders.aggregate([{ $project: { item: 1, revenue: { $multiply: ["$price", "$qty"] } } }, { $sort: { revenue: -1 } }, { $limit: 5 }])

Read the implementation

Connect each part of the code to the concept before you type.

1. Reshape stage

$project chooses which fields to keep and can add computed fields, controlling the document's shape.

{ $project: { item: 1, revenue: { $multiply: ["$price", "$qty"] } } }

2. Keep a field

Setting a field to 1 includes it; setting it to 0 excludes it from the output.

item: 1

3. Computed field

$multiply builds a new field from existing ones; expression operators like $add and $subtract work the same way.

revenue: { $multiply: ["$price", "$qty"] }

4. Order stage

$sort orders documents; -1 is descending and 1 is ascending.

{ $sort: { revenue: -1 } }

5. Limit stage

$limit caps the output to N documents, giving a top-N when it follows $sort.

{ $limit: 5 }

A complete learning loop

01

Understand

Read the concept map and follow the code breakdown.

02

Reconstruct

Type the implementation, repair mistakes and work through every recall exercise.

03

Verify

Use the final check without hints; revisit weak concepts in short practice sessions.

$project & $sort: Lesson & Practice · Typorithm | ApplyDjinn