网站推广员招聘,漳州做网站最便宜,wordpress 自助广告插件,请人做网站多少钱文章目录 语法使用举例 $firstN聚合运算符针对数组返回数组的前n个元素
语法
{ $firstN: { n: expression, input: expression } }n为正整数表达式#xff0c;指定要返回数组的前多少个元素input 为一个数组表达式#xff0c;返回其前n个元素
使用
$firs… 文章目录 语法使用举例 $firstN聚合运算符针对数组返回数组的前n个元素
语法
{ $firstN: { n: expression, input: expression } }n为正整数表达式指定要返回数组的前多少个元素input 为一个数组表达式返回其前n个元素
使用
$firstN返回数组元素的顺序与输入数组元素顺序保持一致$firstN不会过滤掉输入数组中的null值元素如果n大于等于输入数组元素的数量则返回整个数组如果input被解析为空数组聚合操作将报错
举例
使用下面的脚本创建games集合
db.games.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, null, 3489, 9 ]},{ playerId : 6, score : [ 12.1, 2, NumberLong(2090845886852), 23 ]}
])下面的聚合使用$firstN操作符取出每个运动员的三个最高分会使用$addFields将得分放在一个新字段firstScores中
db.games.aggregate([{ $addFields: { firstScores: { $firstN: { n: 3, input: $score } } } }
])操作返回的结果如下
[{playerId: 1,score: [ 1, 2, 3 ],firstScores: [ 1, 2, 3 ]
},
{playerId: 2,score: [ 12, 90, 7, 89, 8 ],firstScores: [ 12, 90, 7 ]
},
{playerId: 3,score: [ null ],firstScores: [ null ]
},
{playerId: 4,score: [ ],firstScores: [ ]
},
{playerId: 5,score: [ 1293, null, 3489, 9 ],firstScores: [ 1293, null, 3489 ]
},
{playerId: 6,score: [ 12.1, 2, NumberLong(2090845886852), 23 ],firstScores: [ 12.1, 2, NumberLong(2090845886852) ]}]