本文為英文版的機器翻譯版本,如內容有任何歧義或不一致之處,概以英文版為準。
$documentNumber
8.0.2 版的新功能。
Amazon DocumentDB 中的 $documentNumber window Operator 會根據$setWindowFields階段sortBy順序,為其分割區中的每個文件傳回不同的序號。與 $rank和 不同$denseRank,它不會特別處理繫結:每個文件都會收到唯一的數字 (例如 1, 2, 3, 4),而具有相同sortBy值的文件會依其遇到的順序編號。它在 $setWindowFields 階段的 output 欄位下指定。
這是僅在$setWindowFields階段中使用的視窗運算子。
參數
-
$documentNumber會將空白文件{}做為其值。 -
它不接受影
window格。 -
它在
$setWindowFields階段中只需要一個sortBy金鑰。
範例 (MongoDB Shell)
下列範例會依 分割文件game、score依遞減順序排序每個分割區,並為每個玩家指派循序文件編號。
建立範例文件
db.players.insertMany([ { _id: 1, game: "A", player: "Alice", score: 90 }, { _id: 2, game: "A", player: "Bob", score: 85 }, { _id: 3, game: "A", player: "Carol", score: 85 }, { _id: 4, game: "A", player: "Dave", score: 70 }, { _id: 5, game: "B", player: "Erin", score: 95 }, { _id: 6, game: "B", player: "Frank", score: 80 } ]);
查詢範例
db.players.aggregate([ { $setWindowFields: { partitionBy: "$game", sortBy: { score: -1 }, output: { documentNumber: { $documentNumber: {} } } } } ]);
輸出
[
{ "_id": 1, "game": "A", "player": "Alice", "score": 90, "documentNumber": 1 },
{ "_id": 2, "game": "A", "player": "Bob", "score": 85, "documentNumber": 2 },
{ "_id": 3, "game": "A", "player": "Carol", "score": 85, "documentNumber": 3 },
{ "_id": 4, "game": "A", "player": "Dave", "score": 70, "documentNumber": 4 },
{ "_id": 5, "game": "B", "player": "Erin", "score": 95, "documentNumber": 1 },
{ "_id": 6, "game": "B", "player": "Frank", "score": 80, "documentNumber": 2 }
]
在每個game分割區中,每個玩家都會以遞減score順序收到不同的序號。Bob 和 Carol 繫結在 ,85但仍會按其遇到23的順序編號。
程式碼範例
若要檢視在$setWindowFields階段中使用 $documentNumber 運算子的程式碼範例,請選擇您要使用之語言的標籤: