Open In App

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.

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

Article Tags :