运算符 $dateToParts 用于从日期对象中提取各个组件(Year、Month、Day、Hour、Minute、Second、Millisecond 等)。 对于需要特定日期部件的作或分析(例如,基于单个日期组件对数据进行排序、筛选或聚合)的情况,运算符非常有用。
Syntax
$dateToParts: {
date: <dateExpression>,
timezone: <string>, // optional
iso8601: <boolean> // optional
}
参数
| 参数 | Description |
|---|---|
date |
要从中提取部件的日期表达式。 |
timezone |
可选。 指定日期的时区。 如果未提供,则默认为 UTC。 |
iso8601 |
可选。 如果为 true,则操作员使用 ISO 8601 周日期日历系统。 默认值为 false。 |
例子
请考虑商店集合中的这个示例文档。
{
"_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:从字段中提取日期部分
此查询用于 $dateToParts 将 lastUpdated 日期分解为年份、月、日和时间等组件。 它有助于分析或转换日期的各个部分以供进一步处理。
db.stores.aggregate([
{
$match: { _id: "e6410bb3-843d-4fa6-8c70-7472925f6d0a" }
},
{
$project: {
_id: 0,
dateParts: {
$dateToParts: {
date: "$lastUpdated"
}
}
}
}
])
此查询返回以下结果。
[
{
"dateParts": {
"year": 2024,
"month": 12,
"day": 4,
"hour": 11,
"minute": 50,
"second": 6,
"millisecond": 0
}
}
]
示例 2:使用时区
此查询使用 lastUpdated $dateToParts提取特定文档的时间戳,并将其分解为日期部分,例如年、月、日和小时。 包括“美国/New_York”时区允许细分,反映当地时间而不是 UTC。
db.stores.aggregate([
{
$match: { _id: "e6410bb3-843d-4fa6-8c70-7472925f6d0a" }
},
{
$project: {
_id: 0,
datePartsWithTimezone: {
$dateToParts: {
date: "$lastUpdated",
timezone: "America/New_York"
}
}
}
}
])
此查询返回以下结果。
[
{
"datePartsWithTimezone": {
"year": 2024,
"month": 12,
"day": 4,
"hour": 6,
"minute": 50,
"second": 6,
"millisecond": 0
}
}
]
相关内容
- 查看有关 从 MongoDB 迁移到适用于 MongoDB 的 Azure Cosmos DB (vCore) 的选项。
- 详细了解 与 MongoDB 的功能兼容性。