SQL >> Base de Datos >  >> NoSQL >> MongoDB

Traducir un MAX de SQL con GROUP BY a una agregación de MongoDB

Empieza por la consulta SQL más interna, la subconsulta:

Select * from tblData Where TFN in (Select TFN From @tmpTFNList) and TrendDate between @StartDate AND @EndDate

El equivalente en MongoDB es un único $match, con $in para la lista y un rango sobre la fecha:

db.getCollection("_core.data").aggregate([
{ "$match": { "TFN": { "$in": tmpTFNList }, "TrendDate": { "$gte": startDate, "$lte": endDate } } }
])

Al añadir el $group obtienes la forma agregada de:

Select TFN, Max(Impressions) MaxImpression from tblData ... Group by TFN
db.getCollection("_core.data").aggregate([
{ "$match": { "TFN": { "$in": tmpTFNList }, "TrendDate": { "$gte": startDate, "$lte": endDate } } },
{ "$group": { "_id": "$TFN", "MaxImpression": { "$max": "$Impression" } } }
])

Y la versión con TOP 5:

Select Top 5 a.TFN, a.MaxImpression as MaxCount from ( ... ) a

requiere un $limit más un $project para renombrar los campos a la salida:

db.getCollection("_core.data").aggregate([
{ "$match": { "TFN": { "$in": tmpTFNList }, "TrendDate": { "$gte": startDate, "$lte": endDate } } },
{ "$group": { "_id": "$TFN", "MaxImpression": { "$max": "$Impression" } } },
{ "$limit": 5 },
{ "$project": { "TFN": "$_id", "_id": 0, "MaxCount": "$MaxImpression" } }
])

Actualización: cuando necesitas la fila con el máximo, no solo el valor

Para el ejemplo de esta edición necesitas un $sort antes del $group, ordenando por TrendDate e Impression en orden descendente. Después, el acumulador $first dentro del $group toma la cima de ese flujo ordenado:

db.getCollection('collection').aggregate([
{ "$match": { "TFN": { "$in": tmpTFNList }, "TrendDate": { "$gte": startDate, "$lte": endDate } } },
{ "$sort": { "TrendDate": -1, "Impression": -1 } },
{ "$group": { "_id": "$TFN", "MaxImpression": { "$first": "$Impression" } } },
{ "$limit": 5 },
{ "$project": { "TFN": "$_id", "_id": 0, "MaxCount": "$MaxImpression" } }
])

Salida de ejemplo

{ "TFN" : 84251456, "MaxCount" : 22 }
{ "TFN" : 84251455, "MaxCount" : 35 }

Un aviso sobre el $limit: limita grupos, no documentos, así que "top 5" significa aquí cinco valores de TFN en el orden que haya producido la agrupación. Si quieres los cinco máximos más altos, añade un $sort por MaxImpression antes del $limit.