MongoDB $sortArray Operator

Beginner
⏱️ 8 min read
📚 Updated: Jul 2026
🎯 4 Examples
Array Operations

What You’ll Learn

The $sortArray operator sorts elements inside an array field and returns a new sorted array. Use it for ordered tag lists, ranked scores, or product line items sorted by price — all within a single document.

01

Sort In-Place

Array field order.

02

input + sortBy

Two-part syntax.

03

1 / -1

Primitives sort.

04

Object arrays

Sort by field.

05

Use Cases

Tags, scores, items.

06

vs $sort

Array vs docs.

Definition and Usage

In MongoDB’s aggregation framework, the $sortArray operator takes an array and a sort specification, then returns a new sorted array. For example, sorting scores descending: { $sortArray: { input: "$scores", sortBy: -1 } } turns [40, 90, 70] into [90, 70, 40].

Unlike the pipeline $sort stage (which orders documents), $sortArray works on array elements within each document. It is available in MongoDB 5.2 and later.

💡
Beginner Tip

Chain with $slice after sorting to get the top N items: sort by score descending, then slice the first 3.

📝 Syntax

The $sortArray operator uses an object with input and sortBy:

mongosh
{
  $sortArray: {
    input: <array expression>,
    sortBy: <sort specification>
  }
}

sortBy for Primitives vs Objects

mongosh
// Array of numbers or strings — use 1 or -1
{ sortBy: 1 }   // ascending
{ sortBy: -1 }  // descending

// Array of documents — use field sort object
{ sortBy: { price: 1 } }
{ sortBy: { score: -1, name: 1 } }

Syntax Rules

  • input — array expression (field path, literal, or nested result).
  • sortBy1/-1 for primitives; object for arrays of documents.
  • Returns a new array; the original field is unchanged unless you assign the result back.
  • Use inside $project, $addFields, or $set.
  • null input returns null.
  • Requires MongoDB 5.2+.

💡 $sortArray vs $sort Stage

$sortArray — sorts elements inside one array field per document
$sort (stage) — sorts documents in the pipeline by top-level fields
Example: sort each user’s scores array → $sortArray
Example: sort users by createdAt{ $sort: { createdAt: -1 } }

⚡ Quick Reference

QuestionAnswer
Operator typeAggregation expression operator (array)
Syntax{ $sortArray: { input, sortBy } }
Primitive sortBy1 (asc) or -1 (desc)
Object array sortBy{ field: 1 | -1, ... }
MongoDB version5.2+
Numbers desc
{
  $sortArray: {
    input: "$scores",
    sortBy: -1
  }
}

Highest first

Tags asc
{
  input: "$tags",
  sortBy: 1
}

A → Z

By price
{
  sortBy: { price: 1 }
}

Object array

Multi-field
{
  sortBy: {
    score: -1,
    name: 1
  }
}

Tie-breaker

Examples Gallery

Sort numeric scores, alphabetize tags, order products by price, and combine with $slice for top-N results using $sortArray.

📚 Sort Primitive Arrays

Order numeric scores and string tags with sortBy: 1 or -1.

Sample Input Documents

Suppose you have a players collection:

mongosh
[
  {
    "_id": 1,
    "name": "Alice",
    "scores": [85, 92, 78, 95],
    "tags": ["beta", "alpha", "gamma"]
  },
  {
    "_id": 2,
    "name": "Bob",
    "scores": [70, 88, 91],
    "tags": ["mongo", "node", "api"]
  }
]

Example 1 — Sort Scores Descending

Return scores from highest to lowest:

mongosh
db.players.aggregate([
  {
    $project: {
      name: 1,
      scoresSorted: {
        $sortArray: {
          input: "$scores",
          sortBy: -1
        }
      }
    }
  }
])

How It Works

For arrays of numbers or strings, sortBy: -1 sorts descending and sortBy: 1 sorts ascending.

Example 2 — Alphabetize Tags

Sort string tags in ascending order:

mongosh
db.players.aggregate([
  {
    $project: {
      name: 1,
      tagsSorted: {
        $sortArray: {
          input: "$tags",
          sortBy: 1
        }
      }
    }
  }
])

// Alice: ["alpha", "beta", "gamma"]
// Bob:   ["api", "mongo", "node"]

How It Works

String sorting follows MongoDB’s default collation order (typically lexicographic).

📈 Object Arrays and Top-N

Sort embedded documents by field and take the top results.

Example 3 — Sort Products by Price

When the array contains objects, use a field-based sortBy:

mongosh
db.orders.aggregate([
  {
    $project: {
      orderId: 1,
      itemsByPrice: {
        $sortArray: {
          input: "$items",
          sortBy: { price: 1 }
        }
      }
    }
  }
])

// items: [
//   { name: "Mouse", price: 25 },
//   { name: "Keyboard", price: 80 },
//   { name: "Cable", price: 10 }
// ]
// itemsByPrice: Cable, Mouse, Keyboard

How It Works

The sortBy object mirrors multi-field $sort syntax. Use { price: -1 } for most expensive first.

Example 4 — Top 3 Scores After Sort

Combine $sortArray with $slice for a leaderboard preview:

mongosh
db.players.aggregate([
  {
    $project: {
      name: 1,
      topThreeScores: {
        $slice: [
          {
            $sortArray: {
              input: "$scores",
              sortBy: -1
            }
          },
          3
        ]
      }
    }
  }
])

// Alice scores [85,92,78,95] → topThree: [95, 92, 85]

How It Works

Sort first, then slice. This pattern is common for “top N” displays without sorting the entire collection.

Bonus — Multi-Field Sort on Object Array

Sort students by grade descending, then by name ascending:

mongosh
db.classes.aggregate([
  {
    $project: {
      className: 1,
      rosterSorted: {
        $sortArray: {
          input: "$students",
          sortBy: { grade: -1, name: 1 }
        }
      }
    }
  }
])

How It Works

MongoDB applies grade first, then uses name to break ties — same rules as collection-level $sort.

🚀 Use Cases

  • Leaderboards — sort scores and slice the top N per player or team.
  • Catalog display — order line items or variants by price or priority inside an order document.
  • Tag and category lists — present alphabetized or ranked tags in the UI.
  • Data normalization — produce consistent array order before comparison with $setEquals.

🧠 How $sortArray Works

1

MongoDB evaluates the input array

The input expression resolves to an array field or computed result.

Input
2

sortBy rules are applied

Primitives use 1/-1. Object arrays use field paths with the same ordering semantics as $sort.

Sort
3

A new sorted array is returned

The original array field is not modified unless you assign the output to replace it.

Output
=

Sorted array

Chain with $slice, $first, or store as a display field.

Conclusion

The $sortArray operator sorts elements within an array field using input and sortBy. Use 1 or -1 for primitive arrays and field objects for arrays of documents.

Remember it sorts array contents, not whole documents — that is the job of the $sort stage. Next in the series: $split.

💡 Best Practices

✅ Do

  • Use $sortArray when order matters inside one document’s array
  • Combine with $slice for top-N leaderboards
  • Use multi-field sortBy when objects share the same primary value
  • Default missing arrays with $ifNull before sorting
  • Verify MongoDB 5.2+ if $sortArray is unavailable

❌ Don’t

  • Confuse $sortArray with the pipeline $sort stage
  • Expect in-place mutation — assign the result to update the field
  • Use field-object sortBy on primitive arrays
  • Forget that null input returns null
  • Sort huge arrays on every request if a pre-sorted cached field works better

Key Takeaways

Knowledge Unlocked

Five things to remember about $sortArray

Use these points when sorting arrays inside MongoDB documents.

5
Core concepts
📝 02

input + sortBy

Two keys.

Syntax
🛠 03

1 / -1

Primitives.

Rule
🗃 04

{ field: 1 }

Object arrays.

Objects
05

vs $sort

Array vs docs.

Important

❓ Frequently Asked Questions

$sortArray returns a new array with elements sorted according to a sort specification. It works on arrays of primitives (numbers, strings) or arrays of documents. The original array field is not modified unless you write the result back.
The syntax is { $sortArray: { input: <array expression>, sortBy: <sort spec> } }. For arrays of primitives, sortBy is 1 (ascending) or -1 (descending). For arrays of objects, sortBy is an object like { price: 1, name: -1 }.
The $sort stage reorders entire documents in the pipeline. $sortArray sorts elements within a single array field on each document. Use $sortArray when you need a sorted list inside one document.
Yes. When the input array contains objects, pass a sortBy object with multiple keys. MongoDB applies the first key, then breaks ties with the second, similar to multi-field $sort on collections.
If input is null or missing, $sortArray returns null. The input must resolve to an array. Use $ifNull to default to an empty array when needed.

Continue the Operator Series

Move on to $split for string splitting, or review $slice for array subsets.

Next: $split →

About the author

Mari Selvan M P
Mari Selvan M P 🔗

Developer, cloud engineer, and technical writer

  • Experience 12 years building web and cloud systems
  • Focus Full Stack Development, AWS, and Developer Education

I write practical tutorials so students and working developers can learn by doing—from databases and APIs to deployment on AWS.

5 people found this page helpful