On this page本页内容
$slice
Returns a subset of an array.返回数组的子集。
$slice
has 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> ] }
<array> | |
<position> |
|
<n> |
|
For more information on expressions, see Expressions.有关表达式的详细信息,请参阅表达式。
{ $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 ] |
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" ] }