$maxN (array operator)
On this page本页内容
Definition定义
Tip
See also: 另请参阅:
Syntax语法
$maxN
has the following syntax:具有以下语法:
{ $maxN: { n: <expression>, input: <expression> } }
n | $maxN returns.$maxN 返回的数组元素数。 |
input | n elements.n 个元素的数组。 |
Behavior行为
You cannot specify a value of不能指定小于n
less than1
.1
的n
值。$maxN
filters out筛选掉null
values found in theinput
array.input
数组中的null
值。If the specified如果指定的n
is greater than or equal to the number of elements in theinput
array,$maxN
returns all elements in theinput
array.n
大于或等于input
数组中的元素数,$maxN
将返回input
数组中所有的元素。If如果input
resolves to a non-array value, the aggregation operation errors.input
解析为非数组值,则聚合操作将出错。If如果输入同时包含数字元素和字符串元素,则字符串元素将根据BSON比较顺序排列在数字元素之前。input
contains both numeric and string elements, the string elements are sorted before numeric elements according to the BSON comparison order.
Example实例
Create a 使用以下文档创建scores
collection with the following documents: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. $maxN
运算符来检索每个玩家的两个最高分数。The highest scores are returned in the new field 最高分数在maxScores
created by $addFields
.$addFields
创建的新字段maxScores
中返回。
db.scores.aggregate([
{ $addFields: { maxScores: { $maxN: { n: 2, input: "$score" } } } }
])
The operation returns the following results:该操作返回以下结果:
[{
"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 ]
}]