MongoDB $reverseArray Operator
MongoDB $reverseArray operator reverses the order of the elements of the specified array.
$reverse Array Operator in MongoDB
The $reverse Array operator in MongoDB is used to reverse the order of a given array. It is an important operator used in the aggregation pipeline to process the data.
It takes an array as an input and returns that array in reversed order. $reverse array operator provides an easy way to change the order of array elements and reverse it.
Syntax
The syntax of the $reverseArray operator is:
{ $reverseArray: <array expression> }
Here, the given arguments must be a valid expression until it resolves to an array.
MongoDB $reverseArray Operator Examples
To understand it better, let’s look at some examples of the $reverseArray Operator in MongoDB.
In the following examples, we are working with:
Database: w3wiki
Collection: arrayExample
Document: three documents that contain the details in the form of field-value pairs.
Using $reverseArray Operator Example
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"}}}])
Using $reverseArray Operator on Array of Strings Example
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 Example
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"}}}])
KeyTakeAways on MongoDB $reverseArray Operator
- The MongoDB $reverseArray operator is used in the aggregation pipeline stages to reverse the order of elements in an array.
- It accepts an array expression as an argument and returns an array with the elements in reverse order.
- 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.