MongoDB $reverseArray Operator

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"}}}])

My Personal Notes arrow_drop_up

Check out this Author's contributed articles.

If you like GeeksforGeeks and would like to contribute, you can also write an article using contribute.geeksforgeeks.org or mail your article to contribute@geeksforgeeks.org. See your article appearing on the GeeksforGeeks main page and help other Geeks.

Please Improve this article if you find anything incorrect by clicking on the "Improve Article" button below.


Article Tags :

Be the First to upvote.


Please write to us at contribute@geeksforgeeks.org to report any issue with the above content.