定义
提示
语法
$maxN 通过以下语法实现:
{ $maxN: { n: <expression>, input: <expression> } }
字段 | 说明 |
|---|---|
| An expression that resolves to a positive integer. The integer specifies the number of array elements that |
| 一个表达式,可解析为要返回最多 |
行为
不能指定小于
1的n值。$maxNfilters outnullvalues found in theinputarray.If the specified
nis greater than or equal to the number of elements in theinputarray,$maxNreturns all elements in theinputarray.如果
input解析为非数组值,则聚合操作将出错。如果
input同时包含数字和string 元素,则根据string BSON比较顺序 , 元素排在数字元素之前。
例子
使用以下文档创建 scores 集合:
db.scores.insertMany([ { "playerId" : 1, "score" : [ 1, 2, 3 ] }, { "playerId" : 2, "score" : [ 12, 90, 7, 89, 8 ] }, { "playerId" : 3, "score" : [ null ] }, { "playerId" : 4, "score" : [ ] } { "playerId" : 5, "score" : [ 1293, "2", 3489, 9 ]} ])
The following example uses the $maxN operator to retrieve the two highest scores for each player. The highest scores are returned in the new field maxScores created by $addFields.
db.scores.aggregate([ { $addFields: { maxScores: { $maxN: { n: 2, input: "$score" } } } } ])
操作返回以下结果:
[{ "playerId": 1, "score": [ 1, 2, 3 ], "maxScores": [ 3, 2 ] }, { "playerId": 2, "score": [ 12, 90, 7, 89, 8 ], "maxScores": [ 90, 89 ] }, { "playerId": 3, "score": [ null ], "maxScores": [ ] }, { "playerId": 4, "score": [ ], "maxScores": [ ] }, { "playerId": 5, "score": [ 1293, "2", 3489, 9 ], "maxScores": [ "2", 3489 ] }]