Database Manual / Reference / Query Language / Expressions

$dateTrunc (aggregation operator)(聚合运算符)

Definition定义

$dateTrunc

New in version 5.0.在版本5.0中新增。

Truncates a date.截断日期。

$dateTrunc syntax:语法:

{
$dateTrunc: {
date: <Expression>,
unit: <Expression>,
binSize: <Expression>,
timezone: <tzExpression>,
startOfWeek: <Expression>
}
}
Field字段Required / Optional必需/可选Description描述
dateRequired必需

The date to truncate, specified in UTC. The date can be any expression that resolves to a Date, a Timestamp, or an ObjectID.要截断的日期,以UTC为单位指定。日期可以是解析为DateTimestampObjectID的任何表达式

unitRequired必需

The unit of time, specified as an expression that must resolve to one of these strings:时间单位,指定为必须解析为以下字符串之一的表达式

  • year
  • quarter
  • week
  • month
  • day
  • hour
  • minute
  • second

Together, binSize and unit specify the time period used in the $dateTrunc calculation.binSizeunit一起指定$dateTrunc计算中使用的时间段。

binSizeOptional可选

The numeric time value, specified as an expression that must resolve to a positive non-zero number. Defaults to 1.数值时间值,指定为必须解析为非零正数的表达式。默认为1。

Together, binSize and unit specify the time period used in the $dateTrunc calculation.binSizeunit一起指定$dateTrunc计算中使用的时间段。

timezoneOptional可选

The timezone for the $dateTrunc calculation, specified as an expression that must resolve to a string that contains one of these values:$dateTrunc计算的时区,指定为必须解析为包含以下值之一的字符串的表达式

If no timezone is provided, the $dateTrunc calculation is performed in UTC.如果没有提供时区,则以UTC执行$dateTrunc计算。

Format格式Examples示例
Olson Timezone Identifier奥尔森时区标识符
  • America/New_York
  • Europe/London
  • GMT
UTC OffsetUTC偏移
  • +/-[hh]:[mm] (example, +04:45)(例如+04:45
  • +/-[hh][mm] (example, -0530)(例如-0530
  • +/-[hh] (example, +03)(例如+03
startOfWeekOptional可选

The start of the week. Used when unit is week. Defaults to Sunday.本周的开始。当unitweek时使用。默认为Sunday

startOfWeek is an expression that must resolve to one of these case insensitive strings:startOfWeek是一个表达式,必须解析为以下不区分大小写的字符串之一:

  • monday (or mon)
  • tuesday (or tue)
  • wednesday (or wed)
  • thursday (or thu)
  • friday (or fri)
  • saturday (or sat)
  • sunday (or sun)

Behavior行为

$dateTrunc:

  • Returns null if:如果满足以下条件,则返回null

    • any of the input fields except startOfWeek is missing or set to null, orstartOfWeek之外的任何输入字段缺失或设置为null,或
    • if unit is week and startOfWeek is missing or set to null.如果unitweek,而startOfWeek缺失或设置为null
  • Uses the proleptic Gregorian calendar for dates preceding the year 1583.1583年之前的日期使用保守的公历
  • Accounts for Daylight Savings Time, but does not account for leap seconds.考虑夏令时,但不考虑闰秒

binSize and unit Fields字段

Together, binSize and unit specify the time period used in the $dateTrunc calculation.binSizeunit一起指定$dateTrunc计算中使用的时间段。

For example:例如:

  • If binSize is 1 and unit is hour, the time period is one hour. For the date 2021-03-20T11:30:05Z, $dateTrunc returns 2021-03-20T11:00:00Z.如果binSize1unithour,则时间段为一小时。对于date 2021-03-20T11:30:05Z$dateTrunc返回2021-03-20T11:00:00Z
  • If binSize is 2 and unit is hour, the time period is two hours. For the date 2021-03-20T11:30:05Z, $dateTrunc returns 2021-03-20T10:00:00Z.如果binSize2unithour,则时间段为两小时。对于date 2021-03-20T11:30:05Z$dateTrunc返回2021-03-20T10:00:00Z

$dateTrunc:

  • Divides the time for the $dateTrunc calculation into binSize time periods in the specified time unit.$dateTrunc计算的时间划分为指定时间unitbinSize时间段。

    The time periods start at a reference date, which is determined by unit. If unit is:时间段从参考日期开始,参考日期由unit确定。如果unit为:

    • A string other than week, $dateTrunc uses a reference date of 2000-01-01T00:00:00.00Z. For example, if binSize is 10 and unit is year, example time periods are:week之外的字符串$dateTrunc使用的参考日期为2000-01-01T00:00:00.00Z。例如,如果binSize10unityear,则示例时间段为:

      • 2000-01-01T00:00:00.00Z
      • 2010-01-01T00:00:00.00Z
      • 2020-01-01T00:00:00.00Z
    • Equal to week, $dateTrunc uses a reference date that is set to the earliest first day of the week that is greater than or equal to 2000-01-01. The first day is set using startOfWeek (the default is Sunday).等于week$dateTrunc使用的参考日期设置为大于或等于2000-01-01的一周中最早的第一天。使用startOfWeek设置第一天(默认值为星期日)。
  • Returns the lower boundary of the time period that the date is in. The boundary is returned as an ISODate. 返回date所在时间段的下限。该边界以ISODate形式返回。If the binSize field is 1, $dateTrunc sets the least significant parts (as determined by unit) of the returned ISODate to 0 and keeps the rest of the ISODate the same.如果binSize字段为1$dateTrunc会将返回的ISODate的最低有效部分(由unit确定)设置为0,并保持ISODate的其余部分不变。

If unit is:如果unit为:

  • year: $dateTrunc returns the ISODate for the start of January 1 for the year in date.$dateTrunc返回date中年份从1月1日开始的ISODate
  • quarter: $dateTrunc returns the ISODate for the start of the first day of the calendar quarter in date.$dateTrunc返回date中日历季度第一天开始的ISODate

    The quarters are:季度是:

    • January to March1月至3月
    • April to June4月至6月
    • July to September7月到9月
    • October to December10月至12月
  • month: $dateTrunc returns the ISODate for the start of the first day of the month in date.$dateTrunc返回date中月份第一天开始的ISODate
  • week: $dateTrunc returns the ISODate for the start of the startOfWeek day in date. The default for startOfWeek is Sunday.$dateTrunc返回datestartOfWeek日开始的ISODatestartOfWeek的默认值是星期日。
  • day: $dateTrunc returns the ISODate for the start of the day in date.$dateTrunc返回date中当天开始的ISODate
  • hour: $dateTrunc returns the ISODate for the start of the hour in date.$dateTrunc返回date中小时开始的ISODate
  • minute: $dateTrunc returns the ISODate for the start of the minute in date.$dateTrunc返回date中分钟开始的ISODate
  • second: $dateTrunc returns the ISODate for start of the second in date.$dateTrunc返回date中第二个开始的ISODate。

unit and startOfWeek Fields字段

If unit is:如果unit为:

  • A string other than week, startOfWeek is ignored.week之外的字符串,startOfWeek将被忽略。
  • Equal to week and startOfWeek is:等于weekstartOfWeek为:

    • Specified: $dateTrunc uses startOfWeek as the first day of the week for the calculation.指定:$dateTrunc使用startOfWeek作为一周的第一天进行计算。
    • Omitted: $dateTrunc uses Sunday as the start of the week for the calculation.省略:$dateTrunc使用周日作为一周的开始进行计算。

Examples示例

Create a cakeSales collection that contains cake sales in the states of California (CA) and Washington (WA):创建一个cakeSales集合,其中包含加利福尼亚州(CA)和华盛顿州(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 }
] )

The cakeSales collection is used in the following examples.以下示例中使用了cakeSales集合。

Truncate Order Dates in a $project Pipeline Stage截断$project管道阶段的订单日期

This example uses $dateTrunc in a $project stage to truncate the cake sales orderDate values to two weeks:此示例在$project阶段使用$dateTrunc将蛋糕销售订单日期值截断为两周:

db.cakeSales.aggregate( [
{
$project: {
_id: 1,
orderDate: 1,
truncatedOrderDate: {
$dateTrunc: {
date: "$orderDate", unit: "week", binSize: 2,
timezone: "America/Los_Angeles", startOfWeek: "Monday"
}
}
}
}
] )

In the example:在示例中:

  • $project includes the _id, orderDate, and truncatedOrderDate fields in the output.输出中包括_idorderDatetruncatedOrderDate字段。
  • $dateTrunc truncates the orderDate field to a 2 binSize week unit time period in the America/Los_Angeles timezone with startOfWeek set to Monday.$dateTruncorderDate字段截断为America/Los_Angeles时区中的2 binSize周单位时间段,startOfWeek设置为Monday

In this example output, the truncated orderDate is shown in the truncatedOrderDate field:在此示例输出中,截断的orderDate显示在截断的orderDate字段中:

[
{
_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")
}
]

Truncate Order Dates and Obtain Quantity Sum in a $group Pipeline Stage截断订单日期并获取$group管道阶段的数量总和

This example uses $dateTrunc in a $group stage to truncate the cake sales orderDate values to six months and return the sum of the quantity values:此示例在$group阶段中使用$dateTrunc将蛋糕销售orderDate值截断为六个月,并返回数量值的总和:

db.cakeSales.aggregate( [
{
$group: {
_id: {
truncatedOrderDate: {
$dateTrunc: {
date: "$orderDate", unit: "month", binSize: 6
}
}
},
sumQuantity: { $sum: "$quantity" }
}
}
] )

In the example:在示例中:

  • $group has the _id field set to the truncatedOrderDate field to group the cakeSales documents, and returns the sum of the quantity values for each group using $sum.$group_id字段设置为truncatedOrderDate字段,以对cakeSales文档进行分组,并使用$sum返回每个组的quantity值之和。
  • $dateTrunc truncates the orderDate field to a 6 binSize month unit time period.orderDate字段截断为6 binSize月单位时间段。

In this example output, the truncated orderDate is shown in the truncatedOrderDate field and the quantity sum is shown in the sumQuantity field:在此示例输出中,截断的orderDate显示在truncatedOrderDate字段中,quantity总和显示在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
}
]