Introduction to MongoDB $reverseArray Operator

$reverseArray is an array operator in the MongoDB aggregation framework that reverses the order of elements in an array. This operator is available in MongoDB version 3.2 and above.

Syntax

The syntax for the $reverseArray operator is as follows:

{ $reverseArray: <expression> }

Where <expression> is an expression that must return an array.

Use Cases

The $reverseArray operator is useful in scenarios where it is necessary to reverse the order of elements in an array. For example, if you need to retrieve a list of comments for an article and display them in chronological order, you can use $reverseArray to reverse the order of the comment list.

Examples

Example 1

The following example demonstrates how to use the $reverseArray operator to reverse the order of elements in an array.

Suppose you have the following document:

{ "_id" : 1, "colors" : [ "red", "green", "blue" ] }

To reverse the colors array, you can use the following aggregation pipeline with the $reverseArray operator:

db.collection.aggregate([
  { $match: { _id: 1 } },
  { $project: { _id: 0, colors: { $reverseArray: "$colors" } } }
])

Running the above pipeline will result in the following output:

{ "colors" : [ "blue", "green", "red" ] }

Example 2

Suppose you have the following order list:

{
  _id: 1,
  orderNumber: "20220001",
  orderItems: [
    { product: "product1", quantity: 1, price: 10 },
    { product: "product2", quantity: 2, price: 20 }
  ]
},
{
  _id: 2,
  orderNumber: "20220002",
  orderItems: [
    { product: "product3", quantity: 3, price: 30 },
    { product: "product4", quantity: 4, price: 40 }
  ]
}

To reverse the order list by order number, you can use the following aggregation pipeline with the $reverseArray operator:

db.orders.aggregate([
  { $sort: { orderNumber: -1 } },
  {
    $project: {
      _id: 0,
      orderNumber: 1,
      orderItems: { $reverseArray: "$orderItems" }
    }
  }
])

Running the above pipeline will result in the following output:

{ "orderNumber" : "20220002", "orderItems" : [ { "product" : "product4", "quantity" : 4, "price" : 40 }, { "product" : "product3", "quantity" : 3, "price" : 30 } ] }
{ "orderNumber" : "20220001", "orderItems" : [ { "product" : "product2", "quantity" : 2, "price" : 20 }, { "product" : "product1", "quantity" : 1, "price" : 10 } ] }

Conclusion

The $reverseArray operator can be used to reverse the order of elements in an array. When using this operator, it is important to note that it can only be used to reverse the order of elements in an array, and cannot modify the elements themselves. In practical applications, the $reverseArray operator is commonly used in scenarios where array elements need to be sorted in reverse order based on time or other criteria.