Open In App

MongoDB $reverseArray Operator

Last Updated : 01 Aug, 2020
Improve
Improve
Like Article
Like
Save
Share
Report

MongoDB provides different types of array expression operators that are used in the aggregation pipeline stages and $reverseArray operator is one of them. This operator is used to reverse the order of the elements of the specified array. Or in other words, this operator takes an array as an argument and returns the array with the items in reverse order.

Syntax: 

{ $reverseArray: <array expression> }

Here, the given arguments must be a valid expression until it resolves to an array.

  •  If the argument does not resolve to an array or null, then this operator will give an error.
  • If the entered argument resolves a null value, then this operator will return null.
  • If the entered argument refers to a missing field, then this operator will return null.
  • If the entered argument is an empty array, then this operator will return an empty array.
  • If the entered argument contains subarrays, then this operator will work on the top-level array elements and will not reverse the contents of subarrays.

 Examples:

In the following examples, we are working with:

Database: GeeksforGeeks

Collection: arrayExample

Document: three documents that contain the details in the form of field-value pairs.

Using $reverseArray Operator:

In this example, we are going to reverse the value of the numbers2 field using $reverseArray operator. Here, the value of the numbers2 field is an array and the elements of the array are numbers.

db.arrayExample.aggregate([
... {$match: {name: "Lolo"}},
... {$project: {
... revNumbers: {$reverseArray: "$numbers2"}}}])

In this example, we are going to reverse the value of the fruits field using $reverseArray operator. Here, the value of the fruits field is an array and the elements of the array are strings(i.e. fruits names).

db.arrayExample.aggregate([
... {$match: {name: "Bongo"}},
... {$project: {
... revStrings: {$reverseArray: "$fruits"}}}])

Using $reverseArray Operator in the Embedded Document:

In this example, we are going to reverse the value of the favGame.outdoorGames field using $reverseArray operator. Here, the value of the favGame.outdoorGames field is an array and the elements of the array are strings(i.e. outdoor games names).

db.arrayExample.aggregate([
... {$match: {name: "Piku"}},
... {$project: {
... result: {$reverseArray: "$favGame.outdoorGames"}}}])


Like Article
Suggest improvement
Previous
Next
Share your thoughts in the comments

Similar Reads