Definition定义
$sliceReturns a subset of an array.返回数组的子集。Note
Disambiguation消歧$slicehas one of two syntax forms:$slice有两种语法形式之一: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.$slice最多返回数组中的最后n个元素。如果指定了ncannot resolve to a negative number if<position>is specified.<position>,则n不能解析为负数。
For more information on expressions, see Expressions.有关表达式的详细信息,请参阅表达式。
Behavior行为
|
|
|
|
|
|
|
|
Example示例
A collection named 名为users contains the following documents:users的集合包含以下文档:
db.users.insertMany( [
{ _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" ] }
]