MongoDB provides the aggregate $dateTrunc operator to truncate the data according to the given date. The $dateTrunc operator only takes the single date value to truncate it in ISO format. The “date” argument of the $dateTrunc takes the date values along with the unit of time. The $dateTrunc operator must require these inputs to truncate the date. Further, we can also use optional arguments such as timezone, binSize, and startOfWeek to lower the boundary of the date within a time range. The $dateTrunc operator divides the time into binSize time intervals in the chosen time unit for calculation.
How to Use the $dateTrunc Operator in MongoDB?
The $dateTrunc operator is used in MongoDB to truncate the given date. Here, we are working with the collection “Flowers” whose documents are used by the $dateTrunc operator for the demonstration. For this, we have to append the documents within the collection “Flowers” by employing the insertMany() method. The output after executing the inserting documents command shows that the documents are now stored inside the “Flowers” collection.
{ _id: 0, type: "Rose", order: new Date("2023-03-23T15:06:20Z"), qty: 100 },
{ _id: 1, type: "Lilly", order: new Date("2021-07-19T12:11:10Z"), qty: 150 },
{ _id: 2, type: "Tulip", order: new Date("2022-12-12T16:14:30Z"), qty: 99 },
{ _id: 3, type: "WhiteRose", order: new Date("2023-08-13T05:10:20Z"), qty: 500 },
{ _id: 4, type: "Lavender", order: new Date("2020-01-01T19:30:10Z"), qty: 200 },
{ _id: 5, type: "SunFlower", order: new Date("2021-03-19T12:12:12Z"), qty: 50 }
] )
Note that there is a field inside the document which is set with the date values. We are going to truncate these dates using the $dateTrunc operator of MongoDB.
insertedIds: [
{ index: 0, _id: 0 },
{ index: 1, _id: 1 },
{ index: 2, _id: 2 },
{ index: 3, _id: 3 },
{ index: 4, _id: 4 },
{ index: 5, _id: 5 }
],
nInserted: 5,
nUpserted: 0,
nMatched: 0,
nModified: 0,
nRemoved: 0,
upserted: []
Example # 1: Using the $dateTrunc Operator to Truncate the Date in MongoDB
Here, we are going to deploy the $dateTrunc operator which simply retrieves the truncated date of the specified date. We have given a query on the MongoDB shell where an aggregate method is employed to carry out the other operators. We called the $project method to include the fields “_id” and “_order” from the matched document. Then, we set another field “truncatedResult” which displayed the results from the $dateTrunc operator. We have defined the $dateTrunc operator which is passed with the parameter “date” and specified with the field “$order” having date values. The $date parameter of the $dateTrunc operator truncated the date with UTC. Next, we have passed the “unit” parameter where the time is expressed as a string “day”. The “day” value indicates that ISODate for the beginning of the day which is returned by $dateTrunc in date.
{
$project: {
_id: 1,
order: 1,
truncatedDate: {
$dateTrunc: {
date: "$order", unit: "day"
}
}
}
}
] )
The output from the above $dateTrunc operator showed the truncated dates of all the document field “order” in the truncateDate field.
{
_id: 0,
order: ISODate("2023-03-23T15:06:20.000Z"),
truncatedDate: ISODate("2023-03-23T00:00:00.000Z")
},
{
_id: 1,
order: ISODate("2021-07-19T12:11:10.000Z"),
truncatedDate: ISODate("2021-07-19T00:00:00.000Z")
},
{
_id: 2,
order: ISODate("2022-12-12T16:14:30.000Z"),
truncatedDate: ISODate("2022-12-12T00:00:00.000Z")
},
{
_id: 3,
order: ISODate("2023-08-13T05:10:20.000Z"),
truncatedDate: ISODate("2023-08-13T00:00:00.000Z")
},
{
_id: 4,
order: ISODate("2020-01-01T19:30:10.000Z"),
truncatedDate: ISODate("2020-01-01T00:00:00.000Z")
},
{
_id: 5,
order: ISODate("2021-03-19T12:12:12.000Z"),
truncatedDate: ISODate("2021-03-19T00:00:00.000Z")
}
]
Example # 2: Using the $dateTrunc Operator With the binSize Argument to Truncate the Date in MongoDB
The optional binSize argument of the $dateTrunc operator is a time value that is expressed as a numerical expression. The numerical expression must be a positive non-zero integer. When the binSize and unit argument are both used together then they define the period for the evaluation of the $dateTrunc operator. We have taken the document whose field “type” value “WhiteRose” which is matched by the $match stage here.
After this, the $dateTrunc operator in the $project operator has been defined to truncate the date using the provided inputs. The $dateTrunc first takes the input “date” where the “$order” field is given as it contains the date values. Then, we have set the “unit” input with the time “hour” and the “binSize” input with the numeric value “2”.
{$match: {"type": "WhiteRose"}},
{
$project: {
_id: 1,
order: 1,
truncatedResult: {
$dateTrunc: {
date: "$order", unit: "hour", binSize: 2
}
}
}
}
] )
The “unit” time is “hour” and the “binSize” has a value of “2”. So, the time between the truncated date return from the $dateTrunc operator and the order date is two hours.
{
_id: 3,
order: ISODate("2023-08-13T05:10:20.000Z"),
truncatedResult: ISODate("2023-08-13T04:00:00.000Z")
}
]
Example # 3: Using the $dateTrunc Operator With the startOfWeek Argument to Truncate the Date in MongoDB
We have another option argument “startOfWeek” of the $dateTrunc operator which specifies the beginning of the week. The “startOfWeek” argument is performed only when the “unit” is the week. Here, we acquire those documents from the $match operator which the $nin operator has not selected in the expression. Then, we deployed the $dateTrunc operator in the $project stage field “truncDate”. The arguments are passed within the $dateTrunc operator to reduce the date. The optional argument “startOfWeek” is also set inside the $dateTrunc operator with the week “Wednesday”. The $dateTrunc operator truncates the “order” field to a “1” binSize and unit “week” time period in the UTC timezone with Wednesday as the startOfWeek.
{ $match : {"_id" : { $nin : [ 1, 3, 5] } } },
{
$project: {
_id: 1,
order: 1,
truncDate: {
$dateTrunc: {
date: "$order", unit: "week", binSize: 1,
timezone: "UTC", startOfWeek: "Wednesday"
}
}
}
}
] )
The results of the $dateTrunc operator are generated with the truncated dates in a “startOfWeek” day as well as the actual date values.
{
_id: 0,
order: ISODate("2023-03-23T15:06:20.000Z"),
truncDate: ISODate("2023-03-22T00:00:00.000Z")
},
{
_id: 2,
order: ISODate("2022-12-12T16:14:30.000Z"),
truncDate: ISODate("2022-12-07T00:00:00.000Z")
},
{
_id: 4,
order: ISODate("2020-01-01T19:30:10.000Z"),
truncDate: ISODate("2020-01-01T00:00:00.000Z")
}
]
Example # 4: Using the $dateTrunc Operator to Return Null in MongoDB
The $dateTrunc operator also returns the null value in a case when the “startOfWeek” inputs the field that is either empty or assigned to null and when the unit argument has the value set as “week” and startOfWeek is not specified or has a null value. Let’s consider this statement with the example script of MongoDB. We have a new inclusion of the field “truncatedOutput” in the $project stage where we have carried out the $dateTrunc operator. The $dateTrunc operator takes the input “date” with the “order” field, the unit as a week, and binSize “2” of an “America/Los_Angeles” timezone. Note that we have not passed the $dateTrunc operator with the “startOfWeek” argument as the week is assigned to the “unit” parameter.
{
$project: {
_id: 1,
order: 1,
truncatedOutput: {
$dateTrunc: {
date: "$orderDate", unit: "week", binSize: 2,
timezone: "America/Los_Angeles"
}
}
}
}
] )
There, we got the null result in the field “truncatedOutput” because we have not input the argument “startOfWeek” into the $dateTrunc operator even though the unit is a week.
{
_id: 0,
order: ISODate("2023-03-23T15:06:20.000Z"),
truncatedOutput: null
},
{
_id: 1,
order: ISODate("2021-07-19T12:11:10.000Z"),
truncatedOutput: null
},
{
_id: 2,
order: ISODate("2022-12-12T16:14:30.000Z"),
truncatedOutput: null
},
{
_id: 3,
order: ISODate("2023-08-13T05:10:20.000Z"),
truncatedOutput: null
},
{
_id: 4,
order: ISODate("2020-01-01T19:30:10.000Z"),
truncatedOutput: null
},
{
_id: 5,
order: ISODate("2021-03-19T12:12:12.000Z"),
truncatedOutput: null
}
]
Example # 5: Using the $dateTrunc Operator to Truncate the Date Inside the $group Operator in MongoDB
We have utilized the $dateTrunc operator in the $group stage of MongoDB which truncates the date within the group key and gets the sum results of the specified field. We have deployed the $group stage and provided a group key “_id” where the new field “TruncDate” is established to perform the $dateTrunc operation. To the $dateTrunc operator, we have input the “date” as an “order” field with the “month” unit time and binSize of “5”. After that, we set another field “AddQuantity” where the $sum operator is assigned with the field $qty for the addition operation.
{
$group: {
_id: {
DateTrunc: {
$dateTrunc: {
date: "$order", unit: "month", binSize: 5
}
}
},
AddQuantity: { $sum: "$qty" }
}
}
] )
The date of the “order” field is truncated to five months using the $dateTrunc operator in a $group stage and the total of the quantity values is also returned in the output.
{
_id: { DateTrunc: ISODate("2020-01-01T00:00:00.000Z") },
AddQuantity: 200
},
{
_id: { DateTrunc: ISODate("2020-11-01T00:00:00.000Z") },
AddQuantity: 50
},
{
_id: { DateTrunc: ISODate("2022-12-01T00:00:00.000Z") },
AddQuantity: 199
},
{
_id: { DateTrunc: ISODate("2021-04-01T00:00:00.000Z") },
AddQuantity: 150
},
{
_id: { DateTrunc: ISODate("2023-05-01T00:00:00.000Z") },
AddQuantity: 500
}
]
Conclusion
We have covered a MongoDB operator $dateTrunc that works with the date to truncate them. We have explored different arguments of the $dateTrunc operator with examples. The $dateTrunc operator only deals with the date field documents in the collection of MongoDB. The $dateTrunc operator is used here with the “binSize” argument and the “startOfWeek” argument which are optional but play an important role while truncating the dates in MongoDB.