$reverseArray (aggregation)

Definition

  • $reverseArray

New in version 3.4.

Accepts an array expression as an argument and returns an array with theelements in reverse order.

$reverseArray has the following operatorexpression syntax:

  1. { $reverseArray: <array expression> }

The argument can be any valid expression as long as it resolves to an array.

Behavior

If the argument resolves to a value of null or refers to amissing field, $reverseArray returns null.

If the argument does not resolve to an array or null nor refersto a missing field, $reverseArray returns an error.

$reverseArray returns an empty array when the argument is an empty array.

If the argument contains subarrays, $reverseArray only operates on the top level array elements and will not reverse the contents of subarrays.

Example [1]Results
  1. { $reverseArray: { $literal: [ 1, 2, 3 ] } }
[ 3, 2, 1 ]
  1. { $reverseArray: { $slice: [ [ "foo", "bar", "baz", "qux" ], 1, 2 ] } }}
[ "baz", "bar" ]
  1. { $reverseArray: null }
null
  1. { $reverseArray: { $literal: [ ] } }
[ ]
  1. { $reverseArray: { $literal: [ [ 1, 2, 3 ], [ 4, 5, 6 ] ] } }
[ [ 4, 5, 6 ], [ 1, 2, 3 ] ]
[1]The examples in the table take a literal argument. To avoid parsingambiguity if the literal argument is an array, you must wrap theliteral array in a $literal expression or keep theouter array that designates the argument list (e.g. [ [ 1, 2, 3 ]] ) to pass in the literal array [1, 2, 3].

Example

A collection named users contains the following documents:

  1. { "_id" : 1, "name" : "dave123", "favorites" : [ "chocolate", "cake", "butter", "apples" ] }
  2. { "_id" : 2, "name" : "li", "favorites" : [ "apples", "pudding", "pie" ] }
  3. { "_id" : 3, "name" : "ahn", "favorites" : [ ] }
  4. { "_id" : 4, "name" : "ty" }

The following example returns an array containing the elements ofthe favorites array in reverse order:

  1. db.users.aggregate([
  2. {
  3. $project:
  4. {
  5. name: 1,
  6. reverseFavorites: { $reverseArray: "$favorites" }
  7. }
  8. }
  9. ])

The operation returns the following results:

  1. { "_id" : 1, "name" : "dave123", "reverseFavorites" : [ "apples", "butter", "cake", "chocolate" ] }
  2. { "_id" : 2, "name" : "li", "reverseFavorites" : [ "pie", "pudding", "apples" ] }
  3. { "_id" : 3, "name" : "ahn", "reverseFavorites" : [ ] }
  4. { "_id" : 4, "name" : "ty", "reverseFavorites" : null }