$slice(聚合)
MongoDB5.0 已于 10 月2024 结束生命周期。不再支持此版本的文档。要升级5.0 部署,请参阅 MongoDB6 。0 升级程序。
定义
行为
例子 | 结果 | ||
---|---|---|---|
|
| ||
|
| ||
|
| ||
|
|
例子
一个名为 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" ] }