$slice (aggregation)
On this page本页内容
Definition定义
$slice-
Returns a subset of an array.返回数组的子集。$slicehas one of two syntax forms:具有两种语法形式之一:The following syntax returns elements from either the start or end of the array:以下语法从数组的开头或结尾返回元素:{ $slice: [ <array>, <n> ] }The following syntax returns elements from the specified position in the array:以下语法从数组中的指定位置返回元素:{ $slice: [ <array>, <position>, <n> ] }Operand运算数Description描述<array>Any valid expression as long as it resolves to an array.任何有效的表达式,只要它解析为数组即可。<position>Optional.可选的。Any valid expression as long as it resolves to an integer.任何有效的表达式,只要它解析为整数即可。If positive,如果为正数,$slicedetermines the starting position from the start of the array.$slice将确定从数组开始的起始位置。If如果<position>is greater than the number of elements, the$slicereturns an empty array.<position>大于元素数,$slice将返回一个空数组。If negative,如果为负数,$slicedetermines the starting position from the end of the array.$slice将确定从数组末尾开始的起始位置。If the absolute value of the如果<position>is greater than the number of elements, the starting position is the start of the array.<position>的绝对值大于元素数,则起始位置为数组的起始位置。
<n>Any valid expression as long as it resolves to an integer.任何有效的表达式,只要它解析为整数即可。If如果指定了<position>is specified,<n>must resolve to a positive integer.<position>,则<n>必须解析为正整数。If positive,如果为正,$slicereturns up to the firstnelements in the array.$slice最多返回数组中的前n个元素。If the如果指定了<position>is specified,$slicereturns the firstnelements starting from the position.<position>,$slice将返回从该位置开始的前n个元素。If negative,如果为负数,$slicereturns up to the lastnelements in the array.ncannot resolve to a negative number if<position>is specified.$slice最多返回数组中的最后n个元素。如果指定了<position>,则n无法解析为负数。
For more information on expressions, see Expressions.有关表达式的详细信息,请参阅表达式。
Behavior行为
{ $slice: [ [ 1, 2, 3 ], 1, 1 ] }
|
[ 2 ]
|
{ $slice: [ [ 1, 2, 3 ], -2 ] }
|
[ 2, 3 ] |
{ $slice: [ [ 1, 2, 3 ], 15, 2 ] }
|
[ ] |
{ $slice: [ [ 1, 2, 3 ], -15, 2 ] }
|
[ 1, 2 ] |
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: [ "pears", "pecans", "chocolate", "cherries" ] }
{ "_id" : 4, "name" : "ty", favorites: [ "ice cream" ] }
The following example returns at most the first three elements in the 以下示例最多为每个用户返回favorites array for each user:favorites数组中的前三个元素:
db.users.aggregate([
{ $project: { name: 1, threeFavorites: { $slice: [ "$favorites", 3 ] } } }
])
The operation returns the following results:该操作返回以下结果:
{ "_id" : 1, "name" : "dave123", "threeFavorites" : [ "chocolate", "cake", "butter" ] }
{ "_id" : 2, "name" : "li", "threeFavorites" : [ "apples", "pudding", "pie" ] }
{ "_id" : 3, "name" : "ahn", "threeFavorites" : [ "pears", "pecans", "chocolate" ] }
{ "_id" : 4, "name" : "ty", "threeFavorites" : [ "ice cream" ] }