In MongoDB, the $reverseArray
aggregation pipeline operator reverses the order of items in an array.
It accepts an array expression as an argument and returns an array with the elements in reverse order.
Example
Suppose we have a collection called products
with the following documents:
{ "_id" : 1, "prod" : "Bat", "sizes" : [ "S", "M", "L" ] } { "_id" : 2, "prod" : "Hat", "sizes" : [ "XS", "S", "L", "XL" ] } { "_id" : 3, "prod" : "Cap", "sizes" : [ "M", "L" ] }
We can use the $reverseArray
operator to reverse the order of those array elements.
Example:
db.products.aggregate(
[
{ $match: { _id: { $in: [ 1, 2, 3 ] } } },
{
$project:
{
_id: 0,
sizes: 1,
reversed: { $reverseArray: [ "$sizes" ] }
}
}
]
)
Result:
{ "sizes" : [ "S", "M", "L" ], "reversed" : [ "L", "M", "S" ] } { "sizes" : [ "XS", "S", "L", "XL" ], "reversed" : [ "XL", "L", "S", "XS" ] } { "sizes" : [ "M", "L" ], "reversed" : [ "L", "M" ] }
Empty Arrays
Passing an empty array returns an empty array.
Sample document:
{ "_id" : 4, "prod" : "Zap", "sizes" : [ ] }
Apply $reverseArray
:
db.products.aggregate(
[
{ $match: { _id: { $in: [ 4 ] } } },
{
$project:
{
_id: 0,
sizes: 1,
reversed: { $reverseArray: [ "$sizes" ] }
}
}
]
)
Result:
{ "sizes" : [ ], "reversed" : [ ] }
Null Values
Passing a value of null
returns null
.
Sample document:
{ "_id" : 5, "prod" : "Tap", "sizes" : null }
Apply $reverseArray
:
db.products.aggregate(
[
{ $match: { _id: { $in: [ 5 ] } } },
{
$project:
{
_id: 0,
sizes: 1,
reversed: { $reverseArray: [ "$sizes" ] }
}
}
]
)
Result:
{ "sizes" : null, "reversed" : null }
Missing Fields
Applying $reverseArray
to a field that doesn’t exist in the document results in null
being returned.
Sample document:
{ "_id" : 6, "prod" : "Map" }
Apply $reverseArray
:
db.products.aggregate(
[
{ $match: { _id: { $in: [ 6 ] } } },
{
$project:
{
_id: 0,
sizes: 1,
reversed: { $reverseArray: [ "$sizes" ] }
}
}
]
)
Result:
{ "reversed" : null }
Wrong Data Type
Applying $reverseArray
to a field that doesn’t resolve to an array results in an error.
Sample document:
{ "_id" : 7, "prod" : "Box", "sizes" : "XXL" }
Apply $reverseArray
:
db.products.aggregate(
[
{ $match: { _id: { $in: [ 7 ] } } },
{
$project:
{
_id: 0,
sizes: 1,
reversed: { $reverseArray: [ "$sizes" ] }
}
}
]
)
Result:
uncaught exception: Error: command failed: { "ok" : 0, "errmsg" : "The argument to $reverseArray must be an array, but was of type: string", "code" : 34435, "codeName" : "Location34435" } : aggregate failed : _getErrorWithCode@src/mongo/shell/utils.js:25:13 doassert@src/mongo/shell/assert.js:18:14 _assertCommandWorked@src/mongo/shell/assert.js:639:17 assert.commandWorked@src/mongo/shell/assert.js:729:16 DB.prototype._runAggregate@src/mongo/shell/db.js:266:5 DBCollection.prototype.aggregate@src/mongo/shell/collection.js:1058:12 @(shell):1:1