MongoDB $sortArray Operator

Beginner
5 min read
Updated: Oct 2026
3 examples
Live preview

What Is $sortArray?

$sortArray is a MongoDB aggregation expression that returns a new sorted array from an input array. Use sortBy: 1 or -1 for numbers and strings, or a field map like { price: 1 } for arrays of documents. Available in MongoDB 5.2+.

Remember
$sortArray = Array.prototype.sort for aggregation

{
  $sortArray: {
    input: <array expression>,
    sortBy: <1 | -1 | { field: 1|-1 }>
  }
}

primitives → sortBy: 1 (asc) or -1 (desc)
documents → sortBy: { field: 1 } or multi-field
null / missing → null
non-array → pipeline error
UsePrefer
Order values inside one array field$sortArray
Reorder whole documents$sort stage
Top N after sorting$sortArray + $slice
Flip order without sorting by value$reverseArray

How to Use $sortArray in MongoDB

Pick the array, choose ascending or descending (or a field map), then emit the sorted result.

  1. Choose an expression stage ($addFields or $project).
  2. Set input to a field path (for example "$scores") or any array expression.
  3. Set sortBy to 1 / -1 for primitives, or { field: 1 } for objects.
  4. Optionally wrap with $slice to keep only the top N items.
PieceRequired?Role
inputYesArray to sort (field, literal, or nested expression)
sortByYes1 / -1, or a document of field directions
$sliceNoTake the first N items after sorting

Pseudocode

Pseudocode
for each document:
    arr = evaluate(input)
    if arr is null or missing:
        result = null
    else if arr is not an array:
        error  // aggregation fails
    else:
        result = sort(arr, sortBy)   // 1 asc, -1 desc, or by fields
    emit { ..., field: result }

Cheat Sheet

Keep these facts handy while writing array-sort expressions.

TopicDetail
TypeAggregation expression (not a find filter)
Syntax{ $sortArray: { input: <array>, sortBy: <spec> } }
PrimitivessortBy: 1 ascending, sortBy: -1 descending
DocumentssortBy: { price: 1 } or { grade: -1, name: 1 }
Top-N pattern$slice: [ { $sortArray: { ... } }, N ]
VersionMongoDB 5.2+
Sample check[85, 92, 78] + sortBy: -1 → [92, 85, 78]

Live Preview

Watch $sortArray reorder a number array. Toggle ascending (1) or descending (-1).

Simulates $sortArray on [85, 92, 78, 95] (same idea as the mongosh examples below).

Result
input  = [85, 92, 78, 95]
sortBy = -1

$sortArray → [95, 92, 85, 78]

{ scoresSorted: [95, 92, 85, 78] }

Worked Walkthrough — Scores Descending

One player has four quiz scores. We want highest first so the top score is easy to read.

Calculation
Document:
  { name: "Alice", scores: [85, 92, 78, 95] }

$sortArray({
  input: "$scores",
  sortBy: -1
})

Compare values (descending):
  95 > 92 > 85 > 78

Result:
  [95, 92, 85, 78]

Check: first element is the max score ✓

MongoDB Examples

We store one player with scores and one order with line items. First we sort numbers, then we sort documents by price. Run these in mongosh after inserting the sample data once.

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.

mongosh
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:

mongosh
db.players.find()
db.orders.find()

Read those documents like this:

Field in MongoDBValuePlain English
scores[85, 92, 78, 95]Quiz scores (unsorted)
items3 product objectsLine items with name and price
items[].price80, 10, 25Sort key for Example 3
Picture
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

  1. Insert once. insertOne adds Alice to players and the order to orders.
  2. Arrays stay as written. Scores and items keep their original order until we sort them.
  3. find() shows the same shape. What you inserted is what you get back—ready for $sortArray next.

Example 2 — Sort Scores Descending

Goal: return Alice’s scores from highest to lowest using sortBy: -1.

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

How It Works

  1. Read the stored array. MongoDB already has scores: [85, 92, 78, 95] from Example 1.
  2. Set direction. sortBy: -1 means larger numbers come first.
  3. Build a new array. $sortArray returns [95, 92, 85, 78] without changing the original scores field in the database.
  4. Keep all fields. $addFields adds scoresSorted next to the original data.

Example 3 — Sort Items by Price

Same idea for an array of documents: pass a field map in sortBy so the cheapest item comes first.

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

How It Works

  1. Same stored order. Still using the three line items from Example 1.
  2. Sort by a field. sortBy: { price: 1 } compares each item’s price ascending.
  3. Whole documents move together. Name and price stay paired—Cable ($10) becomes first.
  4. Easy check. Cheapest → mid → most expensive: 10, 25, 80.

Edge Cases & Pitfalls

Check these before using $sortArray in production pipelines.

vs $sort

Not the same as the $sort stage

$sort reorders documents. $sortArray reorders elements inside one array field.

null

Null and missing become null

Missing array fields return null, not an empty array. Use $ifNull if you want [] instead.

type

Non-array input fails

A string or number in input makes the pipeline error. Confirm the field is an array first.

missing keys

Missing sort fields sort equally

Documents without the sortBy field are treated as equal; their relative order is not guaranteed.

Performance Notes

ApproachCostBest for
$sortArray alonePer document, O(n log n) on array lengthSmall–medium embedded arrays
$sortArray + $sliceSort still runs on the full arrayTop-N previews inside one document
Pipeline $sortCan use indexes on fieldsOrdering many documents in a collection

Large nested arrays cost more to sort. Filter early with $match when only some documents need a sorted array.

Key Takeaways

  • Role: sort elements inside one array field.
  • Primitives: sortBy: 1 or -1.
  • Documents: sortBy: { field: 1 } (multi-field OK).
  • Top N: sort first, then $slice.

One line: $sortArray answers “what does this array look like when ordered?”—inside one document, not across the collection.

Frequently Asked Questions

$sortArray returns a new array with elements ordered by a sort specification. It works on arrays of numbers, strings, or documents. Use it inside aggregation expression stages such as $project and $addFields.
Use { $sortArray: { input: <array expression>, sortBy: <sort spec> } }. For primitives, sortBy is 1 (ascending) or -1 (descending). For objects, use a field map like { price: 1, name: -1 }.
The $sort stage reorders whole documents in the pipeline. $sortArray sorts elements inside one array field on each document. Use $sortArray when order matters within a single document.
Yes. When the array holds documents, pass a sortBy object with multiple keys. MongoDB applies the first key, then breaks ties with the next—same idea as multi-field $sort.
If input is null, missing, or undefined, $sortArray returns null. Any other non-array value causes the aggregation to fail.
$sortArray is available in MongoDB 5.2 and later. Confirm your server version if the operator is rejected.

Next: $split

Split strings into arrays in an aggregation pipeline.

$split tutorial →

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.

9 people found this page helpful