Definição
Novidade na versão 5.0.
Executa operações em um intervalo especificado de documentos em uma collection, conhecido como janela, e retorna os resultados com base no operador de janela escolhido.
For example, you can use the $setWindowFields stage to output the:
Diferença nas vendas entre dois documentos em uma coleção.
Classificações de vendas.
Total cumulativo de vendas.
Análise de informações complexas de séries temporais sem exportar os dados para um banco de dados externo.
Sintaxe
The $setWindowFields stage syntax:
{ $setWindowFields: { partitionBy: <expression>, sortBy: { <sort field 1>: <sort order>, <sort field 2>: <sort order>, ..., <sort field n>: <sort order> }, output: { <output field 1>: { <window operator>: <window operator parameters>, window: { documents: [ <lower boundary>, <upper boundary> ], range: [ <lower boundary>, <upper boundary> ], unit: <time unit> } }, <output field 2>: { ... }, ... <output field n>: { ... } } } }
The $setWindowFields stage takes a document with these fields:
Campo | necessidade | Descrição |
|---|---|---|
Opcional | Specifies an expression to group the documents. In the | |
Necessário para alguns operadores (consulte Restrições) | Especifica o(s) campo(s) para classificar os documentos na partição. Usa a mesma sintaxe do estágio | |
Obrigatório | Specifies the field(s) to append to the documents in the output returned by the A field can contain dots to specify embedded document fields and array fields. The semantics for the embedded document dotted notation in the
| |
Opcional | Especifica os parâmetros e limites da janela. Os limites da janela são inclusivos. O padrão é uma janela sem limite, que inclui todos os documentos na partição. Especifique uma janela de documentos ou faixa. | |
Opcional | Uma janela onde os limites inferior e superior são especificados em relação à posição do documento atual lido na collection. Os limites da janela são especificados usando uma array de dois elementos contendo uma string ou número inteiro de limite inferior e superior. Usar:
Consulte Exemplos de janelas de documentos. | |
Opcional | Uma janela onde os limites inferior e superior são definidos utilizando uma faixa de valores baseada no campo sortBy no documento atual. Os limites da janela são especificados usando uma array de dois elementos contendo uma string ou número de limite inferior e superior. Usar:
Consulte Exemplo de janela de faixa. | |
Opcional |
Dica
Comportamento
The $setWindowFields stage appends new fields to existing documents. You can include one or more $setWindowFields stages in an aggregation operation.
A partir do MongoDB,5.3 você pode usar o $setWindowFields estágio com transações e a "snapshot" preocupação de leitura.
O estágio $setWindowFields não garante a ordem dos documentos retornados.
Operadores de Janela
These operators can be used with the $setWindowFields stage:
- Operadores acumuladores:
$addToSet,$avg,$bottom,$bottomN,$count,$covariancePop,$covarianceSamp,$derivative,$expMovingAvg,$firstN,$integral,$lastN,$max,$maxN,$median,$min,$minN,$percentile,$push,$stdDevSamp,$stdDevPop,$sum,$top,$topN.
- Operadores de preenchimento de lacunas:
$linearFille$locf.
Restrições
Restrictions for the $setWindowFields stage:
Antes do MongoDB,5.3 o estágio não pode ser
$setWindowFieldsusado:Dentro de transações.
Com a read concern
"snapshot".
sortBy é necessário para:
Operações de janela de classificação e ordem.
Janelas com limites (uma janela de documentos ou uma janela de faixa).
$linearFilloperador.
As janelas de faixa de tempo exigem que todos os valores de sortBy sejam datas.
As janelas de faixa e faixa de tempo só podem conter um campo sortBy e a ordem deve ser ascendente.
Você não pode especificar uma janela de documentos e uma janela de faixa.
Estes operadores usam uma janela implícita e retornam um erro se você especificar uma opção de janela:
Operadores de classificação.
$shiftoperador.
For range windows, only numbers in the specified range are included in the window. Missing, undefined, and
nullvalues are excluded.Para janelas de faixa de tempo:
Somente tipos de data e hora são incluídos na janela.
Os valores de limite numéricos devem ser inteiros. Por exemplo, você pode usar 2 horas como limite, mas não pode usar 1,5 hora.
Para janelas vazias ou janelas com valores incompatíveis (por exemplo, utilizando
$sumem strings), o valor retornado depende do operador:Para todos os outros operadores, o valor retornado é
null.
Exemplos
Crie uma collection cakeSales que contenha vendas de bolo nos estados da Califórnia (CA) e de Washington (WA):
db.cakeSales.insertMany( [ { _id: 0, type: "chocolate", orderDate: new Date("2020-05-18T14:10:30Z"), state: "CA", price: 13, quantity: 120 }, { _id: 1, type: "chocolate", orderDate: new Date("2021-03-20T11:30:05Z"), state: "WA", price: 14, quantity: 140 }, { _id: 2, type: "vanilla", orderDate: new Date("2021-01-11T06:31:15Z"), state: "CA", price: 12, quantity: 145 }, { _id: 3, type: "vanilla", orderDate: new Date("2020-02-08T13:13:23Z"), state: "WA", price: 13, quantity: 104 }, { _id: 4, type: "strawberry", orderDate: new Date("2019-05-18T16:09:01Z"), state: "CA", price: 41, quantity: 162 }, { _id: 5, type: "strawberry", orderDate: new Date("2019-01-08T06:12:03Z"), state: "WA", price: 43, quantity: 134 } ] )
Os exemplos a seguir usam a collection cakeSales.
Exemplos de janelas de documentos
Use a janela de documentos para obter a quantidade cumulativa para cada estado
This example uses a documents window in $setWindowFields to output the cumulative cake sales quantity for each state. In the example output, the cumulativeQuantityForState field shows the cumulative quantity for CA and WA.
db.cakeSales.aggregate( [ { $setWindowFields: { partitionBy: "$state", sortBy: { orderDate: 1 }, output: { cumulativeQuantityForState: { $sum: "$quantity", window: { documents: [ "unbounded", "current" ] } } } } } ] )
[ { _id: 4, type: 'strawberry', orderDate: ISODate('2019-05-18T16:09:01.000Z'), state: 'CA', price: 41, quantity: 162, cumulativeQuantityForState: 162 }, { _id: 0, type: 'chocolate', orderDate: ISODate('2020-05-18T14:10:30.000Z'), state: 'CA', price: 13, quantity: 120, cumulativeQuantityForState: 282 }, { _id: 2, type: 'vanilla', orderDate: ISODate('2021-01-11T06:31:15.000Z'), state: 'CA', price: 12, quantity: 145, cumulativeQuantityForState: 427 }, { _id: 5, type: 'strawberry', orderDate: ISODate('2019-01-08T06:12:03.000Z'), state: 'WA', price: 43, quantity: 134, cumulativeQuantityForState: 134 }, { _id: 3, type: 'vanilla', orderDate: ISODate('2020-02-08T13:13:23.000Z'), state: 'WA', price: 13, quantity: 104, cumulativeQuantityForState: 238 }, { _id: 1, type: 'chocolate', orderDate: ISODate('2021-03-20T11:30:05.000Z'), state: 'WA', price: 14, quantity: 140, cumulativeQuantityForState: 378 } ]
No exemplo:
partitionBy: "$state"partitions the documents in the collection bystate. There are partitions forCAandWA.sortBy: { orderDate: 1 }sorts the documents in each partition byorderDatein ascending order (1), so the earliestorderDateis first.
output:Define o campo
cumulativeQuantityForStatepara oquantitycumulativo para cadastate, o que aumenta sucessivamente ao valor anterior na partição.Calcula o
quantitycumulativo utilizando o operador$sumexecutado em uma janela de documentos.The window contains documents between an
unboundedlower limit and thecurrentdocument. This means$sumreturns the cumulativequantityfor the documents between the beginning of the partition and the current document.
Use a janela de documentos para obter a quantidade cumulativa para cada ano
This example uses a documents window in $setWindowFields to output the cumulative cake sales quantity for each $year in orderDate. In the example output, the cumulativeQuantityForYear field shows the cumulative quantity for each year.
db.cakeSales.aggregate( [ { $setWindowFields: { partitionBy: { $year: "$orderDate" }, sortBy: { orderDate: 1 }, output: { cumulativeQuantityForYear: { $sum: "$quantity", window: { documents: [ "unbounded", "current" ] } } } } } ] )
[ { _id: 5, type: 'strawberry', orderDate: ISODate('2019-01-08T06:12:03.000Z'), state: 'WA', price: 43, quantity: 134, cumulativeQuantityForYear: 134 }, { _id: 4, type: 'strawberry', orderDate: ISODate('2019-05-18T16:09:01.000Z'), state: 'CA', price: 41, quantity: 162, cumulativeQuantityForYear: 296 }, { _id: 3, type: 'vanilla', orderDate: ISODate('2020-02-08T13:13:23.000Z'), state: 'WA', price: 13, quantity: 104, cumulativeQuantityForYear: 104 }, { _id: 0, type: 'chocolate', orderDate: ISODate('2020-05-18T14:10:30.000Z'), state: 'CA', price: 13, quantity: 120, cumulativeQuantityForYear: 224 }, { _id: 2, type: 'vanilla', orderDate: ISODate('2021-01-11T06:31:15.000Z'), state: 'CA', price: 12, quantity: 145, cumulativeQuantityForYear: 145 }, { _id: 1, type: 'chocolate', orderDate: ISODate('2021-03-20T11:30:05.000Z'), state: 'WA', price: 14, quantity: 140, cumulativeQuantityForYear: 285 } ]
No exemplo:
partitionBy: { $year: "$orderDate" }partitions the documents in the collection by$yearinorderDate. There are partitions for2019,2020, and2021.sortBy: { orderDate: 1 }sorts the documents in each partition byorderDatein ascending order (1), so the earliestorderDateis first.output:Define o campo
cumulativeQuantityForYearpara oquantitycumulativo para cada ano, que aumenta sucessivamente o valor anterior na partição.Calcula o
quantitycumulativo utilizando o operador$sumexecutado em uma janela de documentos.The window contains documents between an
unboundedlower limit and thecurrentdocument. This means$sumreturns the cumulativequantityfor the documents between the beginning of the partition and the current document.
Use a janela de documentos para obter a quantidade média móvel para cada ano
This example uses a documents window in $setWindowFields to output the moving average for the cake sales quantity. In the example output, the averageQuantity field shows the moving average quantity.
db.cakeSales.aggregate( [ { $setWindowFields: { partitionBy: { $year: "$orderDate" }, sortBy: { orderDate: 1 }, output: { averageQuantity: { $avg: "$quantity", window: { documents: [ -1, 0 ] } } } } } ] )
[ { _id: 5, type: 'strawberry', orderDate: ISODate('2019-01-08T06:12:03.000Z'), state: 'WA', price: 43, quantity: 134, averageQuantity: 134 }, { _id: 4, type: 'strawberry', orderDate: ISODate('2019-05-18T16:09:01.000Z'), state: 'CA', price: 41, quantity: 162, averageQuantity: 148 }, { _id: 3, type: 'vanilla', orderDate: ISODate('2020-02-08T13:13:23.000Z'), state: 'WA', price: 13, quantity: 104, averageQuantity: 104 }, { _id: 0, type: 'chocolate', orderDate: ISODate('2020-05-18T14:10:30.000Z'), state: 'CA', price: 13, quantity: 120, averageQuantity: 112 }, { _id: 2, type: 'vanilla', orderDate: ISODate('2021-01-11T06:31:15.000Z'), state: 'CA', price: 12, quantity: 145, averageQuantity: 145 }, { _id: 1, type: 'chocolate', orderDate: ISODate('2021-03-20T11:30:05.000Z'), state: 'WA', price: 14, quantity: 140, averageQuantity: 142.5 } ]
No exemplo:
partitionBy: "$orderDate"partitions the documents in the collection by$yearinorderDate. There are partitions for2019,2020, and2021.sortBy: { orderDate: 1 }sorts the documents in each partition byorderDatein ascending order (1), so the earliestorderDateis first.output:Define o campo
averageQuantitypara a média móvelquantitypara cada ano.Calcula a média móvel
quantityutilizando o operador$avgexecutado em uma janela de documentos.The window contains documents between
-1and0. This means$avgreturns the moving averagequantitybetween the document before the current document (-1) and the current document (0) in the partition.
Use a janela de documentos para obter a quantidade máxima e cumulativa para cada ano
This example uses a documents window in $setWindowFields to output the cumulative and maximum cake sales quantity values for each $year in orderDate. In the example output, the cumulativeQuantityForYear field shows the cumulative quantity and the maximumQuantityForYear field shows the maximum quantity.
db.cakeSales.aggregate( [ { $setWindowFields: { partitionBy: { $year: "$orderDate" }, sortBy: { orderDate: 1 }, output: { cumulativeQuantityForYear: { $sum: "$quantity", window: { documents: [ "unbounded", "current" ] } }, maximumQuantityForYear: { $max: "$quantity", window: { documents: [ "unbounded", "unbounded" ] } } } } } ] )
[ { _id: 5, type: 'strawberry', orderDate: ISODate('2019-01-08T06:12:03.000Z'), state: 'WA', price: 43, quantity: 134, cumulativeQuantityForYear: 134, maximumQuantityForYear: 162 }, { _id: 4, type: 'strawberry', orderDate: ISODate('2019-05-18T16:09:01.000Z'), state: 'CA', price: 41, quantity: 162, cumulativeQuantityForYear: 296, maximumQuantityForYear: 162 }, { _id: 3, type: 'vanilla', orderDate: ISODate('2020-02-08T13:13:23.000Z'), state: 'WA', price: 13, quantity: 104, cumulativeQuantityForYear: 104, maximumQuantityForYear: 120 }, { _id: 0, type: 'chocolate', orderDate: ISODate('2020-05-18T14:10:30.000Z'), state: 'CA', price: 13, quantity: 120, cumulativeQuantityForYear: 224, maximumQuantityForYear: 120 }, { _id: 2, type: 'vanilla', orderDate: ISODate('2021-01-11T06:31:15.000Z'), state: 'CA', price: 12, quantity: 145, cumulativeQuantityForYear: 145, maximumQuantityForYear: 145 }, { _id: 1, type: 'chocolate', orderDate: ISODate('2021-03-20T11:30:05.000Z'), state: 'WA', price: 14, quantity: 140, cumulativeQuantityForYear: 285, maximumQuantityForYear: 145 } ]
No exemplo:
partitionBy: "$orderDate"partitions the documents in the collection by$yearinorderDate. There are partitions for2019,2020, and2021.sortBy: { orderDate: 1 }sorts the documents in each partition byorderDatein ascending order (1), so the earliestorderDateis first.output:Define o campo
cumulativeQuantityForYearcomoquantitycumulativo para cada ano.Calcula o
quantitycumulativo utilizando o operador$sumexecutado em uma janela de documentos.The window contains documents between an
unboundedlower limit and thecurrentdocument. This means$sumreturns the cumulative quantity for the documents between the beginning of the partition and the current document.Define o campo
maximumQuantityForYearpara aquantitymáxima para cada ano.Calcula a
quantitymáxima de todos os documentos usando o operador$maxexecutado em uma janela de documentos.The window contains documents between an
unboundedlower andupperlimit. This means$maxreturns the maximum quantity for the documents in the partition.
Exemplo de janela de faixa
Este exemplo usa uma janela de faixa em $setWindowFields para retornar a soma dos valores quantity de bolos vendidos para pedidos dentro de mais ou menos 10 dólares do valor price do documento atual. Na saída de exemplo , o campo quantityFromSimilarOrders mostra a soma dos valores quantity para documentos na janela.
db.cakeSales.aggregate( [ { $setWindowFields: { partitionBy: "$state", sortBy: { price: 1 }, output: { quantityFromSimilarOrders: { $sum: "$quantity", window: { range: [ -10, 10 ] } } } } } ] )
[ { _id: 2, type: 'vanilla', orderDate: ISODate('2021-01-11T06:31:15.000Z'), state: 'CA', price: 12, quantity: 145, quantityFromSimilarOrders: 265 }, { _id: 0, type: 'chocolate', orderDate: ISODate('2020-05-18T14:10:30.000Z'), state: 'CA', price: 13, quantity: 120, quantityFromSimilarOrders: 265 }, { _id: 4, type: 'strawberry', orderDate: ISODate('2019-05-18T16:09:01.000Z'), state: 'CA', price: 41, quantity: 162, quantityFromSimilarOrders: 162 }, { _id: 3, type: 'vanilla', orderDate: ISODate('2020-02-08T13:13:23.000Z'), state: 'WA', price: 13, quantity: 104, quantityFromSimilarOrders: 244 }, { _id: 1, type: 'chocolate', orderDate: ISODate('2021-03-20T11:30:05.000Z'), state: 'WA', price: 14, quantity: 140, quantityFromSimilarOrders: 244 }, { _id: 5, type: 'strawberry', orderDate: ISODate('2019-01-08T06:12:03.000Z'), state: 'WA', price: 43, quantity: 134, quantityFromSimilarOrders: 134 } ]
No exemplo:
partitionBy: "$state"partitions the documents in the collection bystate. There are partitions forCAandWA.sortBy: { price: 1 }sorts the documents in each partition bypricein ascending order (1), so the lowestpriceis first.outputdefine o campoquantityFromSimilarOrderscomo a soma dos valoresquantitydos documentos em uma janela de faixa.
Exemplos de janelas de faixa de tempo
Usar uma janela de faixa de tempo com um limite superior positivo
The following example uses a window with a positive upper bound time range unit in $setWindowFields. The pipeline outputs an array of orderDate values for each state that match the specified time range. In the example output, the recentOrders field shows the array of orderDate values for CA and WA.
db.cakeSales.aggregate( [ { $setWindowFields: { partitionBy: "$state", sortBy: { orderDate: 1 }, output: { recentOrders: { $push: "$orderDate", window: { range: [ "unbounded", 10 ], unit: "month" } } } } } ] )
[ { _id: 4, type: 'strawberry', orderDate: ISODate('2019-05-18T16:09:01.000Z'), state: 'CA', price: 41, quantity: 162, recentOrders: [ ISODate('2019-05-18T16:09:01.000Z') ] }, { _id: 0, type: 'chocolate', orderDate: ISODate('2020-05-18T14:10:30.000Z'), state: 'CA', price: 13, quantity: 120, recentOrders: [ ISODate('2019-05-18T16:09:01.000Z'), ISODate('2020-05-18T14:10:30.000Z'), ISODate('2021-01-11T06:31:15.000Z') ] }, { _id: 2, type: 'vanilla', orderDate: ISODate('2021-01-11T06:31:15.000Z'), state: 'CA', price: 12, quantity: 145, recentOrders: [ ISODate('2019-05-18T16:09:01.000Z'), ISODate('2020-05-18T14:10:30.000Z'), ISODate('2021-01-11T06:31:15.000Z') ] }, { _id: 5, type: 'strawberry', orderDate: ISODate('2019-01-08T06:12:03.000Z'), state: 'WA', price: 43, quantity: 134, recentOrders: [ ISODate('2019-01-08T06:12:03.000Z') ] }, { _id: 3, type: 'vanilla', orderDate: ISODate('2020-02-08T13:13:23.000Z'), state: 'WA', price: 13, quantity: 104, recentOrders: [ ISODate('2019-01-08T06:12:03.000Z'), ISODate('2020-02-08T13:13:23.000Z') ] }, { _id: 1, type: 'chocolate', orderDate: ISODate('2021-03-20T11:30:05.000Z'), state: 'WA', price: 14, quantity: 140, recentOrders: [ ISODate('2019-01-08T06:12:03.000Z'), ISODate('2020-02-08T13:13:23.000Z'), ISODate('2021-03-20T11:30:05.000Z') ] } ]
No exemplo:
partitionBy: "$state"partitions the documents in the collection bystate. There are partitions forCAandWA.sortBy: { orderDate: 1 }sorts the documents in each partition byorderDatein ascending order (1), so the earliestorderDateis first.
A janela contém documentos entre um
unboundedlimite inferior e um limite superior definidos como10(10 meses após o valor do documentoorderDateatual) usando uma unidade de faixa de tempo.$pushretorna a array de valoresorderDatepara os documentos entre o início da partição e os documentos com valoresorderDateinclusive em uma faixa do valororderDatedo documento atual mais10meses.
Usar uma janela de faixa de tempo com limite superior negativo
The following example uses a window with a negative upper bound time range unit in $setWindowFields. The pipeline outputs an array of orderDate values for each state that match the specified time range. In the example output, the recentOrders field shows the array of orderDate values for CA and WA.
db.cakeSales.aggregate( [ { $setWindowFields: { partitionBy: "$state", sortBy: { orderDate: 1 }, output: { recentOrders: { $push: "$orderDate", window: { range: [ "unbounded", -10 ], unit: "month" } } } } } ] )
[ { _id: 4, type: 'strawberry', orderDate: ISODate('2019-05-18T16:09:01.000Z'), state: 'CA', price: 41, quantity: 162, recentOrders: [] }, { _id: 0, type: 'chocolate', orderDate: ISODate('2020-05-18T14:10:30.000Z'), state: 'CA', price: 13, quantity: 120, recentOrders: [ ISODate('2019-05-18T16:09:01.000Z') ] }, { _id: 2, type: 'vanilla', orderDate: ISODate('2021-01-11T06:31:15.000Z'), state: 'CA', price: 12, quantity: 145, recentOrders: [ ISODate('2019-05-18T16:09:01.000Z') ] }, { _id: 5, type: 'strawberry', orderDate: ISODate('2019-01-08T06:12:03.000Z'), state: 'WA', price: 43, quantity: 134, recentOrders: [] }, { _id: 3, type: 'vanilla', orderDate: ISODate('2020-02-08T13:13:23.000Z'), state: 'WA', price: 13, quantity: 104, recentOrders: [ ISODate('2019-01-08T06:12:03.000Z') ] }, { _id: 1, type: 'chocolate', orderDate: ISODate('2021-03-20T11:30:05.000Z'), state: 'WA', price: 14, quantity: 140, recentOrders: [ ISODate('2019-01-08T06:12:03.000Z'), ISODate('2020-02-08T13:13:23.000Z') ] } ]
No exemplo:
partitionBy: "$state"partitions the documents in the collection bystate. There are partitions forCAandWA.sortBy: { orderDate: 1 }sorts the documents in each partition byorderDatein ascending order (1), so the earliestorderDateis first.
A janela contém documentos entre um
unboundedlimite inferior e um limite superior definidos como-10(10 meses antes do valor do documentoorderDateatual) usando uma unidade de faixa de tempo.$pushretorna a array deorderDatevalores para os documentos entre o início da partição e os documentos com valoresorderDateinclusive em uma faixa do valororderDatedo documento atual menos10meses.
A seguinte classe WeatherMeasurement representa documentos em uma coleção de medições meteorológicas:
[] public class WeatherMeasurement { [] public ObjectId Id { get; set; } [] public string LocalityId { get; set; } = null!; [] public DateTime MeasurementDateTime { get; set; } [] public float Rainfall { get; set; } [] public float Temperature { get; set; } }
To use the MongoDB .NET/C# driver to add a $setWindowFields stage to an aggregation pipeline, call the UnionWith() method on a PipelineDefinition object.
O exemplo a seguir cria um estágio de pipeline que usa os campos Rainfall e Temperature para calcular a precipitação acumulada, a temperatura média móvel, a temperatura mediana e o 90º percentil de precipitação no mês passado para cada localidade:
var pipeline = new EmptyPipelineDefinition<WeatherMeasurement>() .SetWindowFields( partitionBy: w => w.LocalityId, sortBy: Builders<WeatherMeasurement>.Sort.Ascending( w => w.MeasurementDateTime), output: o => new { MonthlyRainfall = o.Sum( w => w.Rainfall, RangeWindow.Create( RangeWindow.Months(-1), RangeWindow.Current) ), TemperatureAvg = o.Average( w => w.Temperature, RangeWindow.Create( RangeWindow.Months(-1), RangeWindow.Current) ), MedianTemperature = o.Median( w => w.Temperature, RangeWindow.Create( RangeWindow.Months(-1), RangeWindow.Current) ), NinetiethPercentileRainfall = o.Percentile( w => w.Rainfall, new[] { 0.9 }, RangeWindow.Create( RangeWindow.Months(-1), RangeWindow.Current) ) } );
Os exemplos de Node.js nesta página usam a coleção sample_weatherdata.data dos conjuntos de dados de amostra do Atlas. Para aprender como criar um cluster gratuito do MongoDB Atlas e carregar os conjuntos de dados de amostra, consulte Introdução na documentação do driver MongoDB Node.js.
Para usar o driver Node.js do MongoDB para adicionar um estágio $setWindowFields a um pipeline de agregação , use o operador $setWindowFields em um objeto de pipeline.
O exemplo a seguir cria um estágio de pipeline que calcula a média de airTemperature.value e o total de waveMeasurement.waves.height para cada valor único de callLetters no último mês. O exemplo em seguida executa o pipeline de agregação:
const pipeline = [ { $setWindowFields: { partitionBy: "$callLetters", sortBy: { ts: 1 }, output: { temperatureAvg: { $avg: "$airTemperature.value", window: { range: [-1, "current"], unit: "month" } }, totalWaveHeight: { $sum: "$waveMeasurement.waves.height", window: { range: [-1, "current"], unit: "month" } } } } }, ]; const cursor = collection.aggregate(pipeline); return cursor;
Dica
Para obter um exemplo adicional sobre o consumo de energia IOT, consulte o e-book Aggregations práticas do MongoDB.