该 $dateToString 运算符用于将日期对象转换为采用指定格式的字符串。 它通常用于聚合管道,以设置用于报告、查询或显示目的的日期字段的格式。 此运算符非常多才多艺,可用于定义自定义日期格式。
Syntax
{
$dateToString: {
format: "<format_string>",
date: <date_expression>,
timezone: "<timezone>",
onNull: "<replacement_value>"
}
}
参数
| 参数 | Description |
|---|---|
format |
一个指定输出日期格式的字符串。 |
date |
要设置格式的日期表达式。 |
timezone |
(可选)一个指定时区的字符串。 如果未提供,则默认为 UTC。 |
onNull |
(可选)如果字段为date或缺失,则null返回的值。 |
格式说明符
| 符号 | Meaning |
|---|---|
%Y |
年份(四位数) |
%m |
月份(两位数) |
%d |
月份日期(两位数) |
%H |
小时(24 小时,两位数) |
%M |
分钟(两位数) |
%S |
第二个(两位数) |
%L |
毫秒(三位数) |
例子
请考虑商店集合中的这个示例文档。
{
"_id": "0fcc0bf0-ed18-4ab8-b558-9848e18058f4",
"name": "First Up Consultants | Beverage Shop - Satterfieldmouth",
"location": {
"lat": -89.2384,
"lon": -46.4012
},
"staff": {
"totalStaff": {
"fullTime": 8,
"partTime": 20
}
},
"sales": {
"totalSales": 75670,
"salesByCategory": [
{
"categoryName": "Wine Accessories",
"totalSales": 34440
},
{
"categoryName": "Bitters",
"totalSales": 39496
},
{
"categoryName": "Rum",
"totalSales": 1734
}
]
},
"promotionEvents": [
{
"eventName": "Unbeatable Bargain Bash",
"promotionalDates": {
"startDate": {
"Year": 2024,
"Month": 6,
"Day": 23
},
"endDate": {
"Year": 2024,
"Month": 7,
"Day": 2
}
},
"discounts": [
{
"categoryName": "Whiskey",
"discountPercentage": 7
},
{
"categoryName": "Bitters",
"discountPercentage": 15
},
{
"categoryName": "Brandy",
"discountPercentage": 8
},
{
"categoryName": "Sports Drinks",
"discountPercentage": 22
},
{
"categoryName": "Vodka",
"discountPercentage": 19
}
]
},
{
"eventName": "Steal of a Deal Days",
"promotionalDates": {
"startDate": {
"Year": 2024,
"Month": 9,
"Day": 21
},
"endDate": {
"Year": 2024,
"Month": 9,
"Day": 29
}
},
"discounts": [
{
"categoryName": "Organic Wine",
"discountPercentage": 19
},
{
"categoryName": "White Wine",
"discountPercentage": 20
},
{
"categoryName": "Sparkling Wine",
"discountPercentage": 19
},
{
"categoryName": "Whiskey",
"discountPercentage": 17
},
{
"categoryName": "Vodka",
"discountPercentage": 23
}
]
}
]
}
示例 1:将日期字段的格式设置为类似 ISO 的字符串
此查询使用 $dateToString 运算符将 lastUpdated 时间戳格式化为 YYYY-MM-DD 字符串。 它有助于以适合日志、报表或 UI 的可读格式显示日期。
db.stores.aggregate([
{
$match: { _id: "e6410bb3-843d-4fa6-8c70-7472925f6d0a" }
},
{
$project: {
_id: 0,
formattedDate: {
$dateToString: {
format: "%Y-%m-%d",
date: "$lastUpdated"
}
}
}
}
])
此查询返回以下结果。
[
{
"formattedDate": "2024-12-04"
}
]
示例 2:处理 Null 值
此查询使用
db.stores.aggregate([
{
$match: { _id: "e6410bb3-843d-4fa6-8c70-7472925f6d0a" }
},
{
$project: {
_id: 0,
formattedDateOrDefault: {
$dateToString: {
format: "%Y-%m-%d",
date: "$lastUpdated_new", // field doesn't exist
onNull: "No date available"
}
}
}
}
])
此查询返回以下结果。
[
{
"formattedDateOrDefault": "No date available"
}
]
相关内容
- 查看有关 从 MongoDB 迁移到适用于 MongoDB 的 Azure Cosmos DB (vCore) 的选项。
- 详细了解 与 MongoDB 的功能兼容性。