MongoDB $reverseArray Operator

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

What Is $reverseArray?

$reverseArray is a MongoDB aggregation expression that returns a new array with the same elements in reverse order. First becomes last; last becomes first. It does not sort by value—it only flips order.

Remember
$reverseArray ≈ [...arr].reverse()

{ $reverseArray: <arrayExpression> }

[1, 2, 3] → [3, 2, 1]
[]        → []
null / missing → null
non-array (not null) → pipeline error
UsePrefer
Flip existing order$reverseArray
Sort by value$sortArray
Take one element by index$arrayElemAt

How to Use $reverseArray in MongoDB

Pass an array expression; emit the reversed list as a new field.

  1. Choose an expression stage ($addFields or $project).
  2. Pass the array field: { $reverseArray: "$favorites" }.
  3. Optional: guard with $isArray when the field type may vary.
  4. Use the new array in the next stage (slice, elem-at, etc.).
PieceRequired?Role
Array expressionYesField or expression that resolves to an array
Result—New array with reversed top-level order
Nested arrays—Moved as whole elements; not reversed inside

Pseudocode

Pseudocode
for each document:
    arr = evaluate(arrayExpression)
    if arr is null or missing:
        result = null
    else if arr is not an array:
        error
    else:
        result = [ arr[n-1], arr[n-2], ..., arr[0] ]
    emit { ..., field: result }

Cheat Sheet

Keep these facts handy while reversing arrays in pipelines.

TopicDetail
TypeAggregation expression (not a find filter)
Syntax{ $reverseArray: <array> }
Empty array[] → []
Null / missingnull
Nested arraysTop-level reverse only
vs $sortArrayFlip order vs sort by value
Sample["a","b","c"] → ["c","b","a"]

Live Preview

Pick a sample array and watch $reverseArray flip the order.

Simulates $reverseArray (same idea as the mongosh examples). Nested arrays flip only at the top level.

Result
input = ["chocolate", "cake", "apples"]
$reverseArray → ["apples", "cake", "chocolate"]

{ reversed: ["apples", "cake", "chocolate"] }

Worked Walkthrough — Favorites List

Array ["chocolate", "cake", "apples"]. Reverse puts the last favorite first.

Calculation
favorites = ["chocolate", "cake", "apples"]
indexes:       0             1         2

$reverseArray(favorites)
  → ["apples", "cake", "chocolate"]

Empty:  [] → []
Missing field → null

Nested (top level only):
  [[1, 2], [3, 4]] → [[3, 4], [1, 2]]
  // inner [1, 2] stays [1, 2]

MongoDB Examples

We use a small users collection with a favorites array. First we reverse the list, then we read the new first item. Insert the sample data once in mongosh.

Example 1 — Sample Data

Imagine four users. Most have a favorites list; one has an empty list; one has no favorites field.

mongosh
db.users.insertMany([
  { _id: 1, name: "dave123", favorites: ["chocolate", "cake", "apples"] },
  { _id: 2, name: "li", favorites: ["apples", "pie"] },
  { _id: 3, name: "ahn", favorites: [] },
  { _id: 4, name: "ty" }
]);

How the Data Is Stored in MongoDB

After the insert, MongoDB keeps four documents in users. Run find() to see them:

mongosh
db.users.find()

Read those documents like this:

Field in MongoDBExamplePlain English
_id1User id for this lesson
name"dave123"User name
favorites["chocolate", "cake", "apples"]Ordered list (first = earliest)
Picture
dave123 favorites:

  ["chocolate", "cake", "apples"]
   first ───────────────────► last

after $reverseArray:
  ["apples", "cake", "chocolate"]
   last ───────────────────► first

How It Works

  1. Insert once. insertMany adds four user documents.
  2. Order matters. Arrays keep the sequence you wrote—reverse will flip that sequence.
  3. find() shows the same shape. What you inserted is what you get back—ready for $reverseArray next.

Example 2 — Reverse Favorites

Goal: add reversed with the favorites list flipped.

mongosh
db.users.aggregate([
  {
    $addFields: {
      reversed: { $reverseArray: "$favorites" }
    }
  }
]);

How It Works

  1. Read the stored array. "$favorites" is the list for each user.
  2. Flip top-level order. dave123’s last item (apples) moves to index 0.
  3. Empty stays empty. ahn’s [] reverses to [].
  4. Missing → null. ty has no favorites field, so reversed is null.

Example 3 — Reverse Then Take First

Goal: treat the original last favorite as “latest.” Reverse the array, then take index 0 with $arrayElemAt.

mongosh
db.users.aggregate([
  {
    $addFields: {
      latest: {
        $arrayElemAt: [
          { $reverseArray: "$favorites" },
          0
        ]
      }
    }
  }
]);

How It Works

  1. Same stored documents. Still using the four users from Example 1.
  2. Reverse first. Last item moves to the front of a temporary array.
  3. Take index 0. $arrayElemAt(..., 0) reads that new first item as latest.
  4. Shortcut tip. You could also use $arrayElemAt: ["$favorites", -1] for the last item directly—this example shows composing reverse + elem-at.

Edge Cases & Pitfalls

Check these before using $reverseArray in production pipelines.

type

Non-arrays error

A string or number argument fails the pipeline. Guard mixed types with $isArray + $cond.

null

Null / missing → null

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

nested

Only top-level reverse

Nested arrays move as whole elements. Inner order is unchanged unless you reverse those arrays separately.

sort

Not a sort

To order by value, use $sortArray. Reverse only flips whatever order already exists.

Performance Notes

ApproachCostBest for
$reverseArrayO(array length) per docFlipping a known order
+ $arrayElemAtStill O(length)Last-as-first patterns
$arrayElemAt(..., -1)Cheaper for last onlyWhen you only need the last item

Reversing short arrays is cheap. If you only need the last element, prefer $arrayElemAt with index -1 instead of reversing the whole list.

Key Takeaways

  • Role: flip array order (not sort by value).
  • Empty / null: [] → []; missing → null.
  • Nested: top-level elements only.
  • Need last item? $arrayElemAt(..., -1) is enough.

One line: $reverseArray answers “what if this list ran backwards?”—same elements, flipped order.

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. Use it inside aggregation stages such as $project and $addFields.
Use { $reverseArray: <array expression> }. The argument can be a field path like "$favorites" or any expression that resolves to an array.
No. It produces a new value in the pipeline output. The source document stays unchanged unless you write the result back with an update.
If the input is null or the field is missing, $reverseArray returns null. An empty array [] reverses to []. A non-array (and not null) value errors.
$reverseArray only flips the existing order. $sortArray sorts by value (ascending or descending). Use reverse when order is already meaningful and you just want it flipped.
No. It only reverses the top-level elements. Nested arrays stay as-is; only their position in the outer array changes.

Next: $round

Round a number to an integer or a chosen decimal place.

$round 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