Definição
Novidade na versão 5.0.
Trunca uma data.
$dateTrunc sintaxe:
{ $dateTrunc: { date: <Expression>, unit: <Expression>, binSize: <Expression>, timezone: <tzExpression>, startOfWeek: <Expression> } }
Campo | Obrigatório/Opcional | Descrição |
|---|---|---|
Obrigatório | The date to truncate, specified in UTC. The date can be any expression that resolves to a Date, a Timestamp, or an ObjectID. | |
Obrigatório | A unidade de tempo, especificada como uma expressão que deve ser resolvida para uma dessas strings:
Together, binSize and unit specify the time period used in the | |
Opcional | O valor numérico de tempo, especificado como uma expressão que deve ser resolvida para um número positivo diferente de zero. O padrão é 1. Together, binSize and unit specify the time period used in the | |
Opcional | The timezone for the
If no timezone is provided, the | |
Opcional | The start of the week. Used when unit is startOfWeek é uma expressão que deve ser resolvida para uma destas strings sem distinção entre maiúsculas e minúsculas:
|
Dica
Comportamento
Retorna
nullse:any of the input fields except startOfWeek is missing or set to
null, orif unit is
weekand startOfWeek is missing or set tonull.
Usa o calendário gregoriano proléptico para datas anteriores ao ano 1583.
Contabiliza o horário de verão, mas não contabiliza os segundos bissextos.
binSize e unit campos
Together, binSize and unit specify the time period used in the $dateTrunc calculation.
Por exemplo:
If binSize is
1and unit ishour, the time period is one hour. For the date2021-03-20T11:30:05Z,$dateTruncreturns2021-03-20T11:00:00Z.If binSize is
2and unit ishour, the time period is two hours. For the date2021-03-20T11:30:05Z,$dateTruncreturns2021-03-20T10:00:00Z.
Divides the time for the
$dateTrunccalculation into binSize time periods in the specified time unit.The time periods start at a reference date, which is determined by unit. If unit is:
A string other than
week,$dateTruncuses a reference date of2000-01-01T00:00:00.00Z. For example, if binSize is10and unit isyear, example time periods are:2000-01-01T00:00:00.00Z2010-01-01T00:00:00.00Z2020-01-01T00:00:00.00Z
Equal to
week,$dateTruncuses a reference date that is set to the earliest first day of the week that is greater than or equal to2000-01-01. The first day is set using startOfWeek (the default is Sunday).
Se a unidade for:
year:$dateTruncreturns the ISODate for the start of January 1 for the year in date.quarter:$dateTruncreturns the ISODate for the start of the first day of the calendar quarter in date.Os trimestres são:
De janeiro a março
De abril a junho
De julho a setembro
De outubro a dezembro
month:$dateTruncreturns the ISODate for the start of the first day of the month in date.week:$dateTruncreturns the ISODate for the start of the startOfWeek day in date. The default for startOfWeek is Sunday.day:$dateTruncreturns the ISODate for the start of the day in date.hour:$dateTruncreturns the ISODate for the start of the hour in date.minute:$dateTruncreturns the ISODate for the start of the minute in date.second:$dateTruncreturns the ISODate for start of the second in date.
unit e startOfWeek campos
Se a unidade for:
Uma string diferente de
week, startOfWeek é ignorada.Igual a
weeke startOfWeek é:Specified:
$dateTruncuses startOfWeek as the first day of the week for the calculation.Omitted:
$dateTruncuses Sunday as the start of the week for the calculation.
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 } ] )
A coleção cakeSales é utilizada nos seguintes exemplos.
Truncar datas de pedido em um estágio de pipeline $project
This example uses $dateTrunc in a $project stage to truncate the cake sales orderDate values to two weeks:
db.cakeSales.aggregate( [ { $project: { _id: 1, orderDate: 1, truncatedOrderDate: { $dateTrunc: { date: "$orderDate", unit: "week", binSize: 2, timezone: "America/Los_Angeles", startOfWeek: "Monday" } } } } ] )
No exemplo:
$projectinclui os campos_id,orderDateetruncatedOrderDatena saída.$dateTrunctruncates theorderDatefield to a2binSizeweekunit time period in theAmerica/Los_Angelestimezone with startOfWeek set toMonday.
Neste exemplo de saída, o orderDate truncado é mostrado no campo truncatedOrderDate:
[ { _id: 0, orderDate: ISODate("2020-05-18T14:10:30.000Z"), truncatedOrderDate: ISODate("2020-05-11T07:00:00.000Z") }, { _id: 1, orderDate: ISODate("2021-03-20T11:30:05.000Z"), truncatedOrderDate: ISODate("2021-03-15T07:00:00.000Z") }, { _id: 2, orderDate: ISODate("2021-01-11T06:31:15.000Z"), truncatedOrderDate: ISODate("2021-01-04T08:00:00.000Z") }, { _id: 3, orderDate: ISODate("2020-02-08T13:13:23.000Z"), truncatedOrderDate: ISODate("2020-02-03T08:00:00.000Z") }, { _id: 4, orderDate: ISODate("2019-05-18T16:09:01.000Z"), truncatedOrderDate: ISODate("2019-05-13T07:00:00.000Z") }, { _id: 5, orderDate: ISODate("2019-01-08T06:12:03.000Z"), truncatedOrderDate: ISODate("2019-01-07T08:00:00.000Z") } ]
Truncar datas de pedidos e obter soma de quantidade em um $group estágio de pipeline
Este exemplo usa $dateTrunc em um estágio $group para truncar os valores orderDate de vendas do bolo para seis meses e retornar a soma dos valores quantity:
db.cakeSales.aggregate( [ { $group: { _id: { truncatedOrderDate: { $dateTrunc: { date: "$orderDate", unit: "month", binSize: 6 } } }, sumQuantity: { $sum: "$quantity" } } } ] )
No exemplo:
$grouptem o campo_idconfigurado para o campotruncatedOrderDatepara agrupar os documentoscakeSalese retorna a soma dos valoresquantitypara cada grupo utilizando$sum.
Neste exemplo de saída, o orderDate truncado é mostrado no campo truncatedOrderDate e a soma quantity é mostrada no campo sumQuantity :
[ { _id: { truncatedOrderDate: ISODate("2020-01-01T00:00:00.000Z") }, sumQuantity: 224 }, { _id: { truncatedOrderDate: ISODate("2021-01-01T00:00:00.000Z") }, sumQuantity: 285 }, { _id: { truncatedOrderDate: ISODate("2019-01-01T00:00:00.000Z") }, sumQuantity: 296 } ]