Bird
Raised Fist0
MongoDBquery~10 mins

sort method ascending and descending in MongoDB - Step-by-Step Execution

Choose your learning style10 modes available

Start learning this pattern below

Jump into concepts and practice - no test required

or
Recommended
Test this pattern10 questions across easy, medium, and hard to know if this pattern is strong
Concept Flow - sort method ascending and descending
Start with collection
Apply sort method
Specify field and order
MongoDB sorts documents
Return sorted documents
The sort method takes a field and order (1 for ascending, -1 for descending) and returns documents sorted accordingly.
Execution Sample
MongoDB
db.products.find().sort({ price: 1 })
db.products.find().sort({ price: -1 })
This code sorts the 'products' collection by 'price' in ascending and descending order.
Execution Table
StepQuerySort FieldSort OrderResult Order
1db.products.find().sort({ price: 1 })price1 (ascending)[10, 20, 30, 40, 50]
2db.products.find().sort({ price: -1 })price-1 (descending)[50, 40, 30, 20, 10]
3End--Sorting complete, documents returned
💡 Sorting ends after documents are returned in requested order.
Variable Tracker
VariableStartAfter Step 1After Step 2Final
products[{price:30},{price:10},{price:50},{price:20},{price:40}][{price:10},{price:20},{price:30},{price:40},{price:50}][{price:50},{price:40},{price:30},{price:20},{price:10}]Sorted arrays returned
Key Moments - 2 Insights
Why does using 1 sort ascending and -1 sort descending?
In the execution_table rows 1 and 2, 1 means ascending order (smallest to largest), and -1 means descending order (largest to smallest).
Does sort change the original collection data?
No, as shown in variable_tracker, the original 'products' array stays the same; sort returns a new ordered list.
Visual Quiz - 3 Questions
Test your understanding
Look at the execution_table row 1, what is the order of prices after sorting ascending?
A[50, 40, 30, 20, 10]
B[10, 20, 30, 40, 50]
C[30, 10, 50, 20, 40]
D[20, 10, 40, 30, 50]
💡 Hint
Check the 'Result Order' column in row 1 of execution_table.
At which step does the sort order become descending?
AStep 1
BStep 3
CStep 2
DNo descending sort
💡 Hint
Look at the 'Sort Order' column in execution_table rows.
If we change sort({ price: 1 }) to sort({ price: -1 }), how does the variable 'products' change after step 1?
AIt becomes ascending order
BIt becomes descending order
CIt stays unsorted
DIt becomes empty
💡 Hint
Refer to variable_tracker after Step 1 and Step 2 for sorted arrays.
Concept Snapshot
MongoDB sort method:
- Use sort({field: 1}) for ascending order
- Use sort({field: -1}) for descending order
- Returns documents sorted by the field
- Does not modify original data
- Chain after find() to sort query results
Full Transcript
The MongoDB sort method orders documents by a specified field. Using 1 sorts ascending (smallest to largest), and -1 sorts descending (largest to smallest). The method is chained after find() to return sorted results without changing the original collection. For example, sorting products by price ascending returns prices from lowest to highest. Sorting descending reverses this order. This visual shows step-by-step how the sort method changes the order of documents returned.

Practice

(1/5)
1. What does the sort({ age: 1 }) method do in MongoDB?
easy
A. Deletes documents with age less than 1
B. Sorts documents by age in descending order (largest to smallest)
C. Filters documents where age equals 1
D. Sorts documents by age in ascending order (smallest to largest)

Solution

  1. Step 1: Understand the sort method parameter

    The number 1 in sort({ age: 1 }) means ascending order.
  2. Step 2: Interpret the sorting effect

    Documents will be arranged from smallest age to largest age.
  3. Final Answer:

    Sorts documents by age in ascending order (smallest to largest) -> Option D
  4. Quick Check:

    sort({ field: 1 }) = ascending order [OK]
Hint: 1 means ascending order, -1 means descending order [OK]
Common Mistakes:
  • Confusing 1 with descending order
  • Thinking sort filters data
  • Assuming sort deletes documents
2. Which of the following is the correct syntax to sort documents by score in descending order in MongoDB?
easy
A. db.collection.find().sort({ score: -1 })
B. db.collection.find().sort({ score: 1 })
C. db.collection.find().sort(score: -1)
D. db.collection.find().sort({ -1: score })

Solution

  1. Step 1: Check the correct object syntax for sort

    The sort method requires an object with field name as key and 1 or -1 as value, inside curly braces.
  2. Step 2: Identify descending order syntax

    Descending order is indicated by -1, so { score: -1 } is correct.
  3. Final Answer:

    db.collection.find().sort({ score: -1 }) -> Option A
  4. Quick Check:

    sort({ field: -1 }) = descending order [OK]
Hint: Use curly braces and colon: sort({ field: -1 }) [OK]
Common Mistakes:
  • Missing curly braces around sort argument
  • Using parentheses instead of braces
  • Putting -1 as key instead of value
3. Given the documents: [{"name": "Anna", "score": 85}, {"name": "Ben", "score": 92}, {"name": "Cara", "score": 78}], what will be the order of names after running db.students.find().sort({ score: 1 })?
medium
A. ["Ben", "Anna", "Cara"]
B. ["Cara", "Ben", "Anna"]
C. ["Cara", "Anna", "Ben"]
D. ["Anna", "Cara", "Ben"]

Solution

  1. Step 1: Understand ascending sort by score

    Sorting by score ascending means from smallest to largest score: 78, 85, 92.
  2. Step 2: Map scores to names in order

    78 = Cara, 85 = Anna, 92 = Ben, so order is ["Cara", "Anna", "Ben"].
  3. Final Answer:

    ["Cara", "Anna", "Ben"] -> Option C
  4. Quick Check:

    sort({ score: 1 }) = ascending order [OK]
Hint: Ascending sort orders from smallest to largest [OK]
Common Mistakes:
  • Mixing ascending with descending order
  • Sorting by name instead of score
  • Confusing array order in output
4. What is wrong with this MongoDB query?
db.products.find().sort({ price: 2 })
medium
A. The find() method cannot be chained with sort()
B. The sort value must be 1 or -1, not 2
C. The field name 'price' is invalid
D. Missing parentheses after sort

Solution

  1. Step 1: Check valid sort values

    MongoDB sort only accepts 1 for ascending or -1 for descending, not 2.
  2. Step 2: Identify the error cause

    Using 2 will cause a syntax or runtime error because it's invalid.
  3. Final Answer:

    The sort value must be 1 or -1, not 2 -> Option B
  4. Quick Check:

    sort values = 1 or -1 only [OK]
Hint: Sort values must be exactly 1 or -1 [OK]
Common Mistakes:
  • Using numbers other than 1 or -1
  • Assuming any positive number works
  • Thinking sort can't chain after find()
5. You have a collection with documents containing category and price. How do you sort first by category ascending, then by price descending?
hard
A. db.collection.find().sort({ category: 1, price: -1 })
B. db.collection.find().sort({ price: -1, category: 1 })
C. db.collection.find().sort({ category: -1, price: 1 })
D. db.collection.find().sort({ category: 1 }).sort({ price: -1 })

Solution

  1. Step 1: Understand multi-field sort syntax

    MongoDB sorts by fields in the order they appear in the object passed to sort().
  2. Step 2: Apply ascending to category and descending to price

    Use { category: 1, price: -1 } to sort category ascending, then price descending within each category.
  3. Final Answer:

    db.collection.find().sort({ category: 1, price: -1 }) -> Option A
  4. Quick Check:

    Multi-field sort = object with fields in order [OK]
Hint: List fields in sort object in desired priority order [OK]
Common Mistakes:
  • Reversing field order changes sort priority
  • Trying to chain multiple sort() calls
  • Using wrong sort values for fields