Parti dalla query SQL più interna — la subquery:
Select * from tblData
Where TFN in (Select TFN From @tmpTFNList)
and TrendDate between @StartDate AND @EndDate
L'equivalente in MongoDB è un singolo $match, con $in per l'elenco e un intervallo sulla data:
db.getCollection("_core.data").aggregate([
{ "$match": { "TFN": { "$in": tmpTFNList }, "TrendDate": { "$gte": startDate, "$lte": endDate } } }
])
Aggiungendo la $group ottieni la forma aggregata di:
Select TFN, Max(Impressions) MaxImpression from tblData
Where TFN in (Select TFN From @tmpTFNList)
and TrendDate between @StartDate AND @EndDate
Group by TFN
db.getCollection("_core.data").aggregate([
{ "$match": { "TFN": { "$in": tmpTFNList }, "TrendDate": { "$gte": startDate, "$lte": endDate } } },
{ "$group": { "_id": "$TFN", "MaxImpression": { "$max": "$Impression" } } }
])
E la versione con TOP 5:
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
richiede una $limit più una $project per rinominare i campi in uscita:
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" } }
])
Aggiornamento — quando serve la riga con il massimo, non solo il valore
Per il campione di questa modifica, serve una $sort prima della $group, ordinando sia per TrendDate sia per Impression in modo decrescente. Poi l'accumulatore $first all'interno della $group raccoglie la cima di quel flusso ordinato:
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" } }
])
Output di esempio
{ "TFN" : 84251456, "MaxCount" : 22 }
{ "TFN" : 84251455, "MaxCount" : 35 }
Un avvertimento sulla $limit: limita i gruppi, non i documenti. "Top 5" qui significa cinque valori di TFN nell'ordine prodotto dal raggruppamento. Se vuoi i cinque massimi più alti in assoluto, aggiungi una $sort su MaxImpression prima della $limit.