$minN (array operator)
On this page本页内容
Definition定义
$minN
New in version 5.2. 5.2版新增。
Returns the 返回数组中的n smallest values in an array.n个最小值。
Tip
See also: 另请参阅:
Syntax语法
$minN has the following syntax:具有以下语法:
{ $minN: { n: <expression>, input: <expression> } }
n | $minN returns.$minN返回的数组元素数。 |
input | n elements.n个元素的数组。 |
Behavior行为
You cannot specify a value of不能指定小于nless than1.1的n值。$minNfilters outnullvalues found in theinputarray.$minN筛选掉在input数组中找到的code>null值。If the specified如果指定的nis greater than or equal to the number of elements in theinputarray,$minNreturns all elements in theinputarray.n大于或等于input数组中的元素数,$minN将返回输入数组中所有的元素。If如果inputresolves to a non-array value, the aggregation operation errors.input解析为非数组值,则聚合操作将出错。If如果inputcontains both numeric and string elements, the numeric elements are sorted before string elements according to the BSON comparison order.input同时包含数字元素和字符串元素,则数字元素将根据BSON比较顺序排列在字符串元素之前。
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 以下示例使用$minN operator to retrieve the two lowest scores for each player. $minN运算符来检索每个玩家的两个最低分数。The lowest scores are returned in the new field 最低分数在minScores created by $addFields.$addFields创建的新字段minScores中返回。
db.scores.aggregate([
{ $addFields: { minScores: { $minN: { n: 2, input: "$score" } } } }
])
The operation returns the following results:该操作返回以下结果:
[{
"playerId": 1,
"score": [ 1, 2, 3 ],
"minScores": [ 1, 2 ]
},
{
"playerId": 2,
"score": [ 12, 90, 7, 89, 8 ],
"minScores": [ 7, 8 ]
},
{
"playerId": 3,
"score": [ null ],
"minScores": [ ]
},
{
"playerId": 4,
"score": [ ],
"minScores": [ ]
},
{
"playerId": 5,
"score": [ 1293, "2", 3489, 9 ],
"minScores": [ 9, 1293 ]
}]