本文為英文版的機器翻譯版本,如內容有任何歧義或不一致之處,概以英文版為準。
$slice
$slice 彙總運算子可讓您從陣列的開頭或結尾周遊陣列,以傳回陣列的子集。這用於顯示陣列欄位中有限數量的項目,例如頂端或底部 N 個項目。
參數
-
array:要分割的陣列欄位。 -
n:整數,指定要傳回的元素數目。正值從陣列的開頭開始,負值則從陣列的結尾開始。
範例 (MongoDB Shell)
下列範例示範如何使用 $slice傳回每個 Chef 的前兩個最愛甜食。
建立範例文件
db.sweets.insertMany([ { "_id" : 1, "name" : "Alvin", "favorites": [ "chocolate", "cake", "toffee", "beignets" ] }, { "_id" : 2, "name" : "Tom", "favorites": [ "donuts", "pudding", "pie" ] }, { "_id" : 3, "name" : "Jessica", "favorites": [ "fudge", "smores", "pudding", "cupcakes" ] }, { "_id" : 4, "name" : "Rachel", "favorites": [ "ice cream" ] } ]);
查詢範例
db.sweets.aggregate([ { $project: { _id: 0, name: 1, topTwoFavorites: { $slice: [ "$favorites", 2 ] } } } ]);
輸出
[
{ name: 'Alvin', topTwoFavorites: [ 'chocolate', 'cake' ] },
{ name: 'Tom', topTwoFavorites: [ 'donuts', 'pudding' ] },
{ name: 'Jessica', topTwoFavorites: [ 'fudge', 'smores' ] },
{ name: 'Rachel', topTwoFavorites: [ 'ice cream' ] }
]
在此範例中,運算$slice子用於從每個文件的favorites陣列中擷取前兩個元素。
程式碼範例
若要檢視使用 $slice命令的程式碼範例,請選擇您要使用的語言標籤: