本文属于机器翻译版本。若本译文内容与英语原文存在差异,则一律以英文原文为准。
$documentNumber
8.0.2 版中的新内容。
Amazon DocumentDB 中的$documentNumber窗口运算符根据$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但仍处于编号2和3遭遇顺序排列。
代码示例
要查看在$setWindowFields阶段中使用$documentNumber运算符的代码示例,请选择要使用的语言的选项卡: