The Wayback Machine - https://web.archive.org/web/20241124232343/https://www.geeksforgeeks.org/mongodb-reversearray-operator/
Open In App

MongoDB $reverseArray Operator

Last Updated : 24 Jun, 2024
Summarize
Comments
Improve
Suggest changes
Like Article
Like
Save
Share
Report
News Follow

The MongoDB $reverseArray operator is a valuable tool for reversing the order of elements in an array, commonly used for various processing or presentation purposes. In this article, We will learn about the MongoDB $reverseArray Operator by understanding various examples in detail.

MongoDB $reverseArray Operator

  • MongoDB $reverseArray Operator is useful when we need to reverse the order of elements in an array for processing or presentation purposes.
  • $reverseArray provides a straightforward way to manipulate array data in MongoDB.
  • $reverseArray takes an array as an input and returns a new array with the elements 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.

 Examples of MongoDB $reverseArray

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: GeeksforGeeks
Collection: arrayExample
Document: three documents that contain the details in the form of field-value pairs.

Output:

demo database and collection

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

using $reversearray operator example output

Example 2: Using $reverseArray Operator on Array of Strings

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 on array of strings example output

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

using $reversearray operator in the embedded document example output

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.

Conclusion

The MongoDB $reverseArray operator offers a convenient way to reverse the order of elements in an array, providing flexibility in array manipulation within MongoDB documents. Its straightforward syntax and ability to handle various scenarios make it a valuable tool for developers working with array data in MongoDB.

FAQs on MongoDB $reverseArray

Can the $reverseArray operator reverse the contents of subarrays within an array?

No, the $reverseArray operator works only on the top-level array elements and does not reverse the contents of subarrays.

What happens if the argument to $reverseArray is not an array?

If the argument does not resolve to an array or is null, the $reverseArray operator will return an error.

Can $reverseArray be used in update operations to reverse arrays in documents?

No, $reverseArray is used in the aggregation pipeline and cannot be directly used in update operations to modify documents.

Does the $reverseArray operator modify the original array, or does it return a new array with the elements reversed?

$reverseArray returns a new array with the elements in reverse order, leaving the original array unchanged.


Previous Article
Next Article

Similar Reads

How to Integrate MongoDB Atlas and Segment using MongoDB Stitch
Data integration has become a crucial component of modern business strategies, allowing companies to enhance the power of data for informed decision-making. According to a recent survey, 85% of businesses believe that integrating data across multiple platforms is important for their success. In this article, We will learn about What is MongoDB Stit
5 min read
Connect MongoDB Atlas Cluster to MongoDB Compass
MongoDB Compass is a free GUI for MongoDB. You might want to connect MongoDB Atlas Cluster to MongoDB Compass to take benefit of the GUI model for database administration. This guide explains how to connect MongoDB Atlas Cluster to MongoDB Compass. The connection process involves obtaining a connection string from MongoDB Atlas, configuring MongoDB
4 min read
MongoDB Shell vs MongoDB Node.JS Driver
MongoDB Shell and the MongoDB Node.js Driver are both tools for interacting with MongoDB, but they serve different purposes and are used in different contexts. Here's a comparison of the two: MongoDB Node.JS DriverA Node.js package called the MongoDB Node.js Driver enables programmatic communication between applications and MongoDB databases. Throu
4 min read
MongoDB Compass vs MongoDB Atlas
MongoDB is a popular NoSQL database known for flexibility and scalability. MongoDB Compass offers a graphical interface for managing databases visually while MongoDB Atlas is a cloud-based service for automated management and scaling of MongoDB databases. In this article, We will learn about the in-depth understanding of the difference between the
5 min read
MongoDB $sqrt Operator
MongoDB provides different types of arithmetic expression operators that are used in the aggregation pipeline stages $sqrt operator is one of them. This operator is used to find the square root of a positive number and returns the result as a double. Syntax: { $sqrt: <number> } Here, the number is a valid expression until it resolves to a non
2 min read
MongoDB $mod Operator
MongoDB provides different types of arithmetic expression operators that are used in the aggregation pipeline stages and $mod operator is one of them. This operator is used to divide one number by another number and return the remainder. Syntax: { $mod: [ <expression1>, <expression2> ] } Here, in this operator, the arguments passed in a
1 min read
How to use the $lookup operator in aggregation pipelines in MongoDB?
One of the essential stages of the Aggregation Pipeline is the $lookup. It enables us to accomplish a left outer join between two collections. This step is quite beneficial when we have to compose data from different collections into a single document. The Aggregation Pipeline in MongoDB is a robust tool that allows us to manipulate and analyze dat
4 min read
MongoDB - Rename Operator ($rename)
MongoDB $rename operator is a powerful tool for updating field names within documents which ensures data consistency and structure. This operator allows developers to rename fields in a MongoDB collection, including those nested within documents or arrays. In this article, We will learn about the MongoDB $rename by understanding various examples in
4 min read
MongoDB $arrayElemAt Operator
MongoDB $arrayElemAt operator is a key component of the aggregation framework, allowing users to retrieve specific elements from arrays within their documents. In this article, We will learn about the MongoDB $arrayElemAt by understanding various examples in detail and so on. MongoDB $arrayElemAtMongoDB provides different types of array expression
3 min read
MongoDB - $setOnInsert Operator
The $setOnInsert operator in MongoDB is a powerful tool used in updating operations with the upsert option. It allows us to specify values that should be set only when a new document is inserted. In this article, we will learn about the $setOnInsert Operator in MongoDB in detail and so on. MongoDB $setOnInsert OperatorMongoDB $setOnInsert Operator
4 min read
MongoDB - Positional Operator ($)
MongoDB provides a variety of array update operators to modify the values within array fields in documents. One such operator is the positional operator $. This operator allows us to update an element in an array without explicitly specifying the position of that element. In this article, We will learn about the Positional Operator($) in MongoDB in
4 min read
MongoDB $multiply Operator
In MongoDB, the $multiply operator is a powerful tool used in aggregation pipelines to perform multiplication operations. This operator takes one or more expressions as arguments and multiplies them to produce a result. In this article, We will learn about the MongoDB $multiply Operator in detail. MongoDB $multiply OperatorMongoDB provides differen
3 min read
MongoDB $size Operator
MongoDB $size operator is an important tool for calculating the total number of elements within an array. This operator plays a crucial role in MongoDB's aggregation pipeline stages, particularly for tasks requiring the analysis and manipulation of array data. In this article, We will learn about the MongoDB $size Operator by understanding various
3 min read
MongoDB $abs operator
The $abs operator in MongoDB is a fundamental arithmetic expression operator used in aggregation pipeline stages. Its primary function is to calculate the absolute value of a specified number. In this article, We will learn about the MongoDB $abs operator by understanding various examples in detail. MongoDB $abs operatorMongoDB provides different t
3 min read
MongoDB $add Operator
The $add operator in MongoDB is a versatile arithmetic expression operator used to add numbers together or concatenate numbers and dates in the aggregation pipeline. This operator plays an important role in data manipulation and transformation. In this article, We will learn about the MongoDB $add Operator by understanding various examples in detai
3 min read
MongoDB $divide Operator
In MongoDB, the $divide operator is a powerful tool used to perform division between two numerical values. It allows for precise arithmetic operations directly within the database queries, enhancing the capability to manipulate and analyze data. In this article, We will learn about the MongoDB $divide Operator by understanding various examples in d
3 min read
MongoDB $toUpper Operator
The MongoDB $toUpper operator is a powerful tool used to convert string values to uppercase within the aggregation framework. It is particularly useful when working with text data that requires case normalization. In this article, We will learn about the MongoDB $toUpper Operator by understanding various examples in detail. MongoDB $toUpper Operato
3 min read
MongoDB - $pullAll Operator
MongoDB $pullAll operator is a crucial tool for efficiently managing arrays within MongoDB documents. It allows users to remove all instances of specified values from an array and provides a direct way to update array fields. In this article, We will learn about the MongoDB $pullAll Operator by understanding various examples in detail. MongoDB $pul
3 min read
MongoDB $cmp Operator
The MongoDB $cmp operator is a powerful tool for comparing two values within documents, commonly used in aggregation pipelines for sorting or conditional operations. In this article, We will learn about the MongoDB $cmp Operator by understanding various examples in detail. MongoDB $cmp OperatorThe MongoDB $cmp operator is used to compare two values
3 min read
MongoDB $ceil Operator
In MongoDB, the $ceil operator is a powerful tool used in aggregation pipelines to round numbers up to the nearest integer greater than or equal to the original number. In this article, We will learn about the MongoDB $ceil Operator in detail. MongoDB $ceil OperatorMongoDB $ceil operator is used in aggregation pipelines to perform mathematical roun
3 min read
MongoDB $floor Operator
In MongoDB, the $floor operator is a powerful tool in aggregation pipelines that allow for the rounding down of numbers to the nearest integer less than or equal to the original number. In this article, We will learn about the MongoDB $floor Operator in detail by understanding various examples and so on. MongoDB $floor OperatorMongoDB $floor operat
3 min read
MongoDB $exp Operator
MongoDB's aggregation framework provides a powerful set of tools for data manipulation and processing. One such tool is the $exp operator which allows users to perform exponential calculations within aggregation pipelines. In this article, We will learn about the MongoDB $exp Operator in detail. MongoDB $exp OperatorThe $exp operator in MongoDB is
3 min read
MongoDB - $mul Operator
MongoDB $mul operator is a powerful update operator used to multiply the value of a field by a specified number. This operator allows for direct arithmetic operations within the database, making it particularly useful for scenarios that require modifying numeric field values without needing to retrieve the current value first. In this article, We w
4 min read
MongoDB $strcasecmp Operator
$strcasecmp operator in MongoDB is a string expression operator used to perform case-insensitive comparisons between two strings. It is commonly utilized within the aggregation pipeline to facilitate these comparisons. In this article, We will learn about the MongoDB $strcasecmp Operator by understanding various examples. MongoDB $strcasecmp Operat
3 min read
MongoDB All Positional Operator ($[])
The MongoDB $[] positional operator is a powerful tool used to update all elements in an array that match a specified condition. When working with arrays in MongoDB, this operator helps identify and modify every element that meets the query criteria. In this article, We will learn about the MongoDB All Positional Operator ($[]) by understanding var
4 min read
MongoDB Bitwise Update Operator
The MongoDB Bitwise Update Operator allows for efficient manipulation of integer fields within MongoDB documents through bitwise operations. In this article, We will learn about the MongoDB Bitwise Update Operator in detail by understanding various examples in detail. MongoDB Bitwise Update OperatorMongoDB Bitwise Update Operator allows performing
3 min read
MongoDB $substrCP Operator
The $substrCP operator in MongoDB is a powerful tool used within the aggregation framework to extract substrings from strings based on Unicode code points. This makes it particularly effective for handling strings with non-ASCII characters. In this article, We will learn about the MongoDB $substrCP by understanding the various examples in detail. $
4 min read
MongoDB $pow Operator
MongoDB's $pow operator is a powerful tool within the aggregation framework which is designed to compute exponentiation operations directly on numeric fields. In this article, We will learn about the MongoDB $pow Operator in detail by understanding various examples and so on. MongoDB $pow OperatorThe MongoDB $pow operator is a mathematical aggregat
4 min read
MongoDB $log10 Operator
In MongoDB, the $log10 operator is a powerful tool that allows users to perform mathematical computations directly within the database. This operator returns the base 10 logarithm of a specified number and making it invaluable for data analysis and transformation tasks. In this article, We will learn about the MongoDB $log10 Operator by understandi
3 min read
MongoDB $concatArrays Operator
The $concatArrays operator in MongoDB is one of the many array expression operators available for use in aggregation pipeline stages. It is particularly useful for combining arrays from different fields or documents within a collection. In this article, We will learn about the MongoDB $concatArrays in detail by understanding various examples and so
3 min read
Article Tags :
three90RightbarBannerImg