$slice(聚合)
定义
行为
例子 | 结果 | ||
---|---|---|---|
|
| ||
|
| ||
|
| ||
|
|
例子
一个名为 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" ] }
以下示例最多会返回每个用户的 favorites
数组中的前三个元素:
db.users.aggregate([ { $project: { name: 1, threeFavorites: { $slice: [ "$favorites", 3 ] } } } ])
操作返回以下结果:
{ "_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" ] }