$minN (aggregation accumulator)
Nesta página
Definição
Sintaxe
{ $minN: { input: <expression>, n: <expression> } }
input
specifies an expression that is the input to$minN
. It is evaluated for each element in the group and$minN
preserves the minimumn
values.n
limita o número de resultados por grupo en
deve ser uma expressão integral positiva que seja constante ou dependa do valor_id
para$group
.
Comportamento
Tipo de resultado
$minN
compares input data following the
BSON Comparison order to
determine the appropriate output type. When the input data contains
multiple data types, the $minN
output type is the lowest
in the comparison order.
Valores nulos e ausentes
$minN
filtra valores nulos e ausentes.
Consider the following aggregation that returns the minimum n
documents from a group:
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 } } } } ] )
Neste exemplo:
$documents
cria os documentos literais que contêm as pontuações dos jogadores.$group
agrupa os documentos porgameId
. Este exemplo tem apenas umgameId
,G1
.PlayerD
has a missing score andPlayerE
has a nullscore
. These values are both ignored.O campo
minimumThreeScores
é especificado como$minN
cominput : "$score"
e retornado como uma array.Since there are only 3 documents with
scores
minN
returns the minimum 3score
fields even thoughn = 4
.
[ { _id: 'G1', minimumThreeScores: [ 1, 2, 3 ] } ]
Comparação de acumuladores $minN
e $bottomN
Both $minN
and $bottomN
accumulators can accomplish
similar results.
Em geral:
Restrições
Suporte para função de janela e expressão de agregação
Você pode usar $minN
como acumulador.
$minN
é suportado como uma expressão de aggregation.
$minN
é suportado como window operator
.
Considerações sobre o limite de memória
Os pipelines de agregação que chamam $minN
estão sujeitos ao limite de 100 MB. Se esse limite for excedido para um grupo individual, a agregação falhará com um erro.
Exemplos
Considere uma collection gamescores
com os seguintes documentos:
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 } ])
Find the Minimum Three Scores
for a Single Game
You can use the $minN
accumulator to find the minimum three scores
in a single game.
db.gamescores.aggregate( [ { $match : { gameId : "G1" } }, { $group: { _id: "$gameId", minScores: { $minN: { input: ["$score","$playerId"], n:3 } } } } ] )
O exemplo de pipeline:
Utiliza
$match
para filtrar os resultados em um únicogameId
. Neste caso,G1
.Utiliza
$group
para agrupar os resultados porgameId
. Neste caso,G1
.Especifica os campos que são entrada para
$minN
cominput : ["$score","$playerId"]
.Uses
$minN
to return the first three score elements for theG1
game withn : 3
.
A operação retorna os seguintes resultados:
[ { _id: 'G1', minScores: [ [ 1, 'PlayerD' ], [ 31, 'PlayerA' ], [ 33, 'PlayerB' ] ] } ]
Finding the Minimum Three Documents Across Multiple Games
You can use the $minN
accumulator to find the minimum n
scores in each game.
db.gamescores.aggregate( [ { $group: { _id: "$gameId", minScores: { $minN: { input: ["$score","$playerId"], n: 3 } } } } ] )
O exemplo de pipeline:
Utiliza
$group
para agrupar os resultados porgameId
.Uses
$minN
to return the minimum three score elements for each game withn: 3
.Especifica os campos que são entrada para
$minN
cominput: ["$score","$playerId"]
.
A operação retorna os seguintes resultados:
[ { _id: 'G2', minScores: [ [ 10, 'PlayerA' ], [ 14, 'PlayerB' ], [ 66, 'PlayerC' ] ] }, { _id: 'G1', minScores: [ [ 1, 'PlayerD' ], [ 31, 'PlayerA' ], [ 33, 'PlayerB' ] ] } ]
Computação n
com base na chave de grupo para $group
Você também pode atribuir o valor de n
dinamicamente. Neste exemplo, a expressão $cond
é utilizada no campo gameId
.
db.gamescores.aggregate([ { $group: { _id: {"gameId": "$gameId"}, gamescores: { $minN: { input: ["$score","$playerId"], n: { $cond: { if: {$eq: ["$gameId","G2"] }, then: 1, else: 3 } } } } } } ] )
O exemplo de pipeline:
Utiliza
$group
para agrupar os resultados porgameId
.Especifica os campos que entram para
$minN
cominput : ["$score","$playerId"]
.Se
gameId
forG2
entãon
é 1, caso contrárion
é 3.
A operação retorna os seguintes resultados:
[ { _id: { gameId: 'G2' }, gamescores: [ [ 10, 'PlayerA' ] ] }, { _id: { gameId: 'G1' }, gamescores: [ [ 1, 'PlayerD' ], [ 31, 'PlayerA' ], [ 33, 'PlayerB' ] ] } ]