MongoDB Tutorial 0/120 lessons ~6 min read Lesson 38

    Sorting Results

    Sort orders the cursor.

    Course progress0%
    Focus
    5 guided sections
    Practice signal
    Examples included
    Career prep
    Foundation builder

    Introduction

    Sort orders the cursor. The trick: sorting on an unindexed field forces an in-memory sort, which is capped at ~32 MB and will error out for large result sets. Always sort on an index.

    Syntax reference

    js
    db.posts.find().sort({ createdAt: -1 }).limit(20);

    Real-world use

    Every 'newest first' or 'top liked' list relies on indexed sort.

    Best practices

    • Match sort key with an index (compound is fine).
    • Combine filter + sort fields in one compound index.

    Common mistakes

    • In-memory sort fails over 32 MB — check explain.
    Ready to mark this lesson complete?Track your journey across the entire course.