$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
配列の最初の 3 つの要素が返されます。
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" ] }