sql >> Base de Datos >  >> NoSQL >> MongoDB

Max y group by en Mongodb

Para lograr el resultado deseado, comience desglosando la consulta SQL comenzando con la subconsulta:

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

La consulta mongo equivalente sigue:

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

El $group equivalente agregado de

Select TFN, Max(Impressions) MaxImpression 
from tblData 
Where TFN in (Select TFN From @tmpTFNList) and TrendDate between @StartDate AND @EndDate
Group by TFN 

sigue

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

Las 5 consultas principales

Select Top 5 a.TFN, a.MaxImpression as MaxCount from ( 
    Select TFN, Max(Impressions) MaxImpression 
    from tblData 
    Where TFN in (Select TFN From @tmpTFNList) 
        and TrendDate between @StartDate AND @EndDate
    Group by TFN 
) a

es posible con $limit operador y la selección de campos a través del $project actuar como

db.getCollection("_core.data").aggregate([
    { /* WHERE TFN in list AND TrendDate between DATES */
        "$match": {
            "TFN": { "$in": tmpTFNList },
            "TrendDate": {
                "$gte": startDate,
                "$lte": endDate
            }
        }
    },
    { /* GROUP BY TFN */
        "$group": {
            "_id": "$TFN",
            "MaxImpression": { "$max": "$Impression" }
        }
    },
    { "$limit": 5 }, /* TOP 5 */
    { /* SELECT a.MaxImpression as MaxCount */
        "$project": {
            "TFN": "$_id",
            "_id": 0,
            "MaxCount": "$MaxImpression"
        }
    }
])

ACTUALIZAR

Para obtener el resultado deseado de la muestra en esta editar , necesita un $sort tubería antes del $group donde ordena los documentos por TrendDate y Impression campos, ambos en orden descendente.

Luego deberá usar el $first operador acumulador dentro del $group etapa de canalización para obtener la máxima impresión, ya que tendrá un flujo ordenado de documentos en su canalización.

Considere ejecutar la operación agregada revisada como:

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 muestra

/* 1 */
{
    "TFN" : 84251456,
    "MaxCount" : 22
}

/* 2 */
{
    "TFN" : 84251455,
    "MaxCount" : 35
}