$reverseArray (aggregation)

On this page本页内容

Definition定义

$reverseArray

Accepts an array expression as an argument and returns an array with the elements in reverse order.接受数组表达式作为参数,并返回元素顺序相反的数组。

$reverseArray has the following operator expression syntax:具有以下运算符表达式语法

{ $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 a missing field, $reverseArray returns null.如果参数解析为null值或引用缺少的字段,$reverseArray将返回null

If the argument does not resolve to an array or null nor refers to a missing field, $reverseArray returns an error.如果参数未解析为数组或null,也未引用缺少的字段,$reverseArray将返回错误。

$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.如果参数包含子数组,则$reverseArray仅对顶级数组元素进行操作,不会反转子数组的内容。

Example [1]Results
{ $reverseArray: { $literal: [ 1, 2, 3 ] } }
[ 3, 2, 1 ]
{ $reverseArray:
   { $slice:  [ [ "foo", "bar", "baz", "qux" ], 1, 2 ] } }
}
[ "baz", "bar" ]
{ $reverseArray: null }
null
{ $reverseArray: { $literal: [ ] } }
[ ]
{ $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 parsing ambiguity if the literal argument is an array, you must wrap the literal array in a $literal expression or keep the outer array that designates the argument list (e.g. [ [ 1, 2, 3 ] ] ) to pass in the literal array [1, 2, 3].如果文字参数是数组,为了避免解析歧义,必须将文字数组包装在$literal表达式中,或者保留指定参数列表的外部数组(例如[ [ 1, 2, 3 ] ]),以传入文字数组[1, 2, 3]

Example示例

A collection named users contains the following documents:名为users的集合包含以下文档:

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

The following example returns an array containing the elements of the favorites array in reverse order:以下示例以相反的顺序返回包含favorites数组元素的数组:

db.users.aggregate([
   {
     $project:
      {
         name: 1,
         reverseFavorites: { $reverseArray: "$favorites" }
      }
   }
])

The operation returns the following results:该操作返回以下结果:

{ "_id" : 1, "name" : "dave123", "reverseFavorites" : [ "apples", "butter", "cake", "chocolate" ] }
{ "_id" : 2, "name" : "li", "reverseFavorites" : [ "pie", "pudding", "apples" ] }
{ "_id" : 3, "name" : "ahn", "reverseFavorites" : [ ] }
{ "_id" : 4, "name" : "ty", "reverseFavorites" : null }
←  $replaceAll (aggregation)$round (aggregation) →