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"}}}])
MongoDB $reverseArray Operator
MongoDB $reverseArray operator reverses the order of the elements of the specified array.
Contact Us