MongoDB $reverseArray Operator

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

What You’ll Learn

The $reverseArray operator flips the order of elements in an array inside MongoDB aggregation pipelines. Use it to show newest-first timelines, reorder tags, or prepare data for downstream stages like $slice.

01

Flip Order

Last becomes first.

02

One Argument

Any array expression.

03

New Array

Does not mutate source.

04

Aggregation

$project / $addFields.

05

Use Cases

Timelines, stacks.

06

vs $sortArray

Reverse vs sort.

Definition and Usage

In MongoDB’s aggregation framework, the $reverseArray operator accepts an array and returns a new array with elements in reverse order. For example, reversing ["a", "b", "c"] gives ["c", "b", "a"].

This is useful when data is stored oldest-first but you want to display newest-first, or when you need the last items in a sequence without changing how they were saved. The original document field is not modified unless you explicitly write the result back.

💡
Beginner Tip

$reverseArray flips position only — it does not sort by value. To order numbers or strings by their values, use $sortArray instead.

📝 Syntax

The $reverseArray operator takes a single array expression:

mongosh
{ $reverseArray: <array expression> }

Examples of Valid Input

mongosh
{ $reverseArray: "$tags" }
{ $reverseArray: [1, 2, 3] }
{ $reverseArray: { $slice: ["$history", 5] } }

Syntax Rules

  • Argument — any expression that evaluates to an array (field path or literal).
  • Output — a new array with elements in reverse index order.
  • Empty array[] reverses to [].
  • Null / missing — returns null when input is null or missing.
  • Nested arrays — reverses top-level elements only; inner arrays stay as-is.
  • Use inside $project, $addFields, or $set (MongoDB 3.4+).

💡 $reverseArray vs $sortArray vs $slice

$reverseArray — flips existing order (index reversal)
$sortArray — sorts elements by value or a sort key
$slice — returns a portion of an array (first or last N items)
Combine — reverse then slice to get “last 3 in original order” as first 3 in output

⚡ Quick Reference

QuestionAnswer
Operator typeAggregation expression operator (array)
Syntax{ $reverseArray: <array> }
OutputNew array, elements in reverse order
Mutates source?No (pipeline produces new value)
Common stages$project, $addFields, $set
Field path
{
  $reverseArray: "$tags"
}

Reverse field

Literal
{
  $reverseArray: [1, 2, 3]
}

→ [3, 2, 1]

Empty
[] → []

No change

Null input
null

Returns null

Examples Gallery

Reverse tag lists, flip activity timelines, combine with $slice, and handle empty arrays with $reverseArray.

📚 Basic Array Reversal

Flip the order of a tags array with $reverseArray.

Sample Input Documents

Suppose you have a articles collection:

mongosh
[
  {
    "_id": 1,
    "title": "MongoDB Basics",
    "tags": ["database", "nosql", "tutorial"]
  },
  {
    "_id": 2,
    "title": "Empty Tags",
    "tags": []
  },
  {
    "_id": 3,
    "title": "Activity Log",
    "events": ["created", "edited", "published"]
  }
]

Example 1 — Reverse a Tags Array

Flip the order of tags for display:

mongosh
db.articles.aggregate([
  {
    $project: {
      title: 1,
      tags: 1,
      tagsReversed: {
        $reverseArray: "$tags"
      }
    }
  }
])

How It Works

Element at index 0 moves to the end, and the last element moves to index 0. The original tags field in the document is unchanged; only tagsReversed is added in the output.

📈 Practical Patterns

Newest-first feeds, last-N items, and nested pipeline expressions.

Example 2 — Newest-First Activity Feed

Show events with the most recent action first:

mongosh
db.articles.aggregate([
  {
    $match: { events: { $exists: true } }
  },
  {
    $project: {
      title: 1,
      recentFirst: {
        $reverseArray: "$events"
      }
    }
  }
])

// events: ["created", "edited", "published"]
// recentFirst: ["published", "edited", "created"]

How It Works

If events were appended in chronological order, reversing gives a newest-first list for UI display without re-sorting by timestamp.

Example 3 — Reverse Then Take First 2

Get the two most recent events (last two in the original array):

mongosh
db.articles.aggregate([
  {
    $project: {
      title: 1,
      latestTwo: {
        $slice: [
          { $reverseArray: "$events" },
          2
        ]
      }
    }
  }
])

// latestTwo: ["published", "edited"]

How It Works

Reverse puts the last original items at the front. $slice with a positive count takes the first two elements of that reversed array.

Example 4 — Replace Field With Reversed Copy

Overwrite tags in the pipeline output with the reversed order:

mongosh
db.articles.aggregate([
  {
    $project: {
      title: 1,
      tags: {
        $reverseArray: "$tags"
      }
    }
  }
])

// tags in output: ["tutorial", "nosql", "database"]

How It Works

Projecting tags with $reverseArray replaces the field value in the aggregation result. To persist this change, use $merge or an update based on the pipeline output.

Bonus — Reverse Leaderboard Order

Flip a pre-sorted scores array for bottom-to-top display:

mongosh
db.games.aggregate([
  {
    $project: {
      game: 1,
      topScores: "$scores",
      bottomUp: {
        $reverseArray: "$scores"
      }
    }
  }
])

// scores: [980, 850, 720]
// bottomUp: [720, 850, 980]

How It Works

$reverseArray does not sort — it assumes scores is already ordered high-to-low and simply inverts that order.

🚀 Use Cases

  • UI display — show newest-first timelines, comments, or notifications.
  • Stack simulation — treat a FIFO list as LIFO for processing logic.
  • Last-N extraction — combine with $slice after reversing.
  • Data transformation — reorder arrays in ETL without application-side code.

🧠 How $reverseArray Works

1

MongoDB evaluates the array expression

The pipeline resolves the argument to an array value, field path, or nested expression result.

Input
2

Indexes are swapped end to end

Element at index 0 moves to the last position; the last moves to index 0, and so on.

Reverse
3

A new array is returned

The output is a fresh array. The source document field is not modified by the operator itself.

Output
=

Reversed element order

Use in projections, or chain with $slice and $map.

Conclusion

The $reverseArray operator returns a new array with elements in reverse index order. It is a simple, fast way to flip timelines, stacks, or any ordered list inside aggregation pipelines.

Remember: it reverses position, not value. For value-based ordering, use $sortArray. Next in the series: $round.

💡 Best Practices

✅ Do

  • Use $reverseArray for index-order flips (newest-first feeds)
  • Combine with $slice to get the last N original items
  • Handle null input with $ifNull when the field may be missing
  • Use $sortArray when you need value-based ordering
  • Keep original and reversed fields side by side when debugging

❌ Don’t

  • Expect $reverseArray to sort numbers or strings by value
  • Assume nested arrays are reversed internally (only top level flips)
  • Forget that aggregation output does not auto-update stored documents
  • Reverse huge arrays repeatedly without considering pipeline cost
  • Confuse index reversal with descending sort

Key Takeaways

Knowledge Unlocked

Five things to remember about $reverseArray

Use these points when reversing arrays in pipelines.

5
Core concepts
📝 02

One argument

Array expression.

Syntax
🛠 03

New array

Non-destructive.

Output
🗃 04

+ $slice

Last N items.

Chaining
05

[] / null

Empty or missing.

Edge case

❓ Frequently Asked Questions

$reverseArray returns a new array with the elements of the input array in reverse order. The first element becomes last, and the last becomes first. It does not modify the original array field in the document.
The syntax is { $reverseArray: <array expression> }. Use inside $project, $addFields, or $set. The argument can be a field path like "$tags" or any expression that evaluates to an array.
No. Aggregation operators produce new values in the pipeline output. The source document's array field stays unchanged unless you write the reversed result back with $set or a similar update outside the pipeline.
If the input resolves to null or is missing, $reverseArray returns null. An empty array [] reverses to an empty array.
$reverseArray only flips the existing order — it does not sort by value. To sort ascending or descending by a field, use $sortArray instead.

Continue the Operator Series

Move on to $round for numeric rounding, or review $map to transform array elements.

Next: $round →

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