赞
踩
$minN
聚合运算符用于返回聚合分组中最小的n个元素,如果分组中的元素数量小于n,则返回分组的全部元素。
{
$minN:
{
input: <expression>,
n: <expression>
}
}
参数说明:
input
:指定输入表达式,表达式用于对分组中的每个元素计算后,$minN
保留最小的n个值。n
:用于指定每个分组中要返回的成员数量,n
必须是正整数,可以是常量或者依赖于分组内的_id
值。$minN
会过滤掉空值和缺失值下面的聚合返回分组中最小的n
个文档:
db.aggregate( [ { $documents: [ { playerId: "PlayerA", gameId: "G1", score: 1 }, { playerId: "PlayerB", gameId: "G1", score: 2 }, { playerId: "PlayerC", gameId: "G1", score: 3 }, { playerId: "PlayerD", gameId: "G1" }, { playerId: "PlayerE", gameId: "G1", score: null } ] }, { $group: { _id: "$gameId", minimumThreeScores: { $minN: { input: "$score", n: 4 } } } } ] )
在这个例子中:
$document
创建了一个常量文档,包含了运动员的得分$group
根据gameId
对文档进行分组,例子中只有一个gameId
,G1
PlayerD
的得分缺失,PlayerE
的得分为空,这些值都被视为空$minN
和input:"$score"
返回一个数组放在maximumThreeScores
字段n=4
,但因为只有3个文档有得分,$minN
只返回得分最低的3个[
{
_id: 'G1',
minimumThreeScores: [ 1, 2, 3 ]
}
]
$minN
和$bottomN
这两个运算符可以得到相同的结果,通常的:
$minN
会更有优势。$bottomN
$minN
$minN
可以被用作累加器$minN
也支持作为聚合表达式$minN
同时也支持作为窗口运算符在聚合管道中使用$minN
时,受100M的限制,如果单个分组唱过这一限制,聚合将报错。
使用下面的脚本创建gamescores
集合:
db.gamescores.insertMany([
{ playerId: "PlayerA", gameId: "G1", score: 31 },
{ playerId: "PlayerB", gameId: "G1", score: 33 },
{ playerId: "PlayerC", gameId: "G1", score: 99 },
{ playerId: "PlayerD", gameId: "G1", score: 1 },
{ playerId: "PlayerA", gameId: "G2", score: 10 },
{ playerId: "PlayerB", gameId: "G2", score: 14 },
{ playerId: "PlayerC", gameId: "G2", score: 66 },
{ playerId: "PlayerD", gameId: "G2", score: 80 }
])
下面的聚合使用$minN
找出一个项目中后三名的得分
db.gamescores.aggregate( [ { $match : { gameId : "G1" } }, { $group: { _id: "$gameId", minScores: { $minN: { input: ["$score","$playerId"], n:3 } } } } ] )
在这个例子中:
$match
筛选出gameId
为G1
的项目$group
根据gameId
进行分组,本例中只有一个分组G1
input : ["$score","$playerId"]
为$minN
指定输入字段$minN
返回G1
比赛项目中得分最低的三个元素结果如下:
[
{
_id: 'G1',
minScores: [ [ 1, 'PlayerD' ], [ 31, 'PlayerA' ], [ 33, 'PlayerB' ] ]
}
]
下面的聚合使用$minN
在所有项目中,查找n个得分最低的
db.gamescores.aggregate( [ { $group: { _id: "$gameId", minScores: { $minN: { input: ["$score","$playerId"], n: 3 } } } } ] )
本例中:
$group
依据gameId
进行分组$minN
返回所有项目中得分最低的3个input:["$score","$playerId"]
为$minN
指定输入字段返回结果如下:
[
{
_id: 'G2',
minScores: [ [ 10, 'PlayerA' ], [ 14, 'PlayerB' ], [ 66, 'PlayerC' ] ]
},
{
_id: 'G1',
minScores: [ [ 1, 'PlayerD' ], [ 31, 'PlayerA' ], [ 33, 'PlayerB' ] ]
}
]
n
的值可以动态指定,在下面的例子中,$cond
表达式用于gameId
字段
db.gamescores.aggregate([ { $group: { _id: {"gameId": "$gameId"}, gamescores: { $minN: { input: ["$score","$playerId"], n: { $cond: { if: {$eq: ["$gameId","G2"] }, then: 1, else: 3 } } } } } } ] )
本例中:
$group
依据gameId
进行分组input:["$score","$playerId"]
为$minN
指定输入字段gameId
为G2
则n
为1,否则n
为3操作返回结果:
[
{ _id: { gameId: 'G2' }, gamescores: [ [ 10, 'PlayerA' ] ] },
{
_id: { gameId: 'G1' },
gamescores: [ [ 1, 'PlayerD' ], [ 31, 'PlayerA' ], [ 33, 'PlayerB' ] ]
}
]
Copyright © 2003-2013 www.wpsshop.cn 版权所有,并保留所有权利。