运算符 $dateFromParts
从各个组件(如年份、月、日、小时、分钟、秒和毫秒)构造日期。 处理单独存储日期组件的数据时,此运算符非常有用。
语法
{ $dateFromParts: { year: <year>, month: <month>, day: <day>, hour: <hour>, minute: <minute>, second: <second>, millisecond: <millisecond>, timezone: <timezone> } }
参数
参数 | 说明 |
---|---|
year |
日期的年份部分。 |
month |
日期的月份组件。 |
day |
日期的日期部分。 |
hour |
日期的小时部分。 |
minute |
日期的分钟分量。 |
second |
日期的第二个组成部分。 |
millisecond |
日期的毫秒部分。 |
timezone |
可选。 时区规范。 |
例子
让我们了解 stores
数据集中的示例 json 的用法。
{
"_id": "e6410bb3-843d-4fa6-8c70-7472925f6d0a",
"name": "Relecloud | Toy Collection - North Jaylan",
"location": {
"lat": 2.0797,
"lon": -94.4134
},
"staff": {
"employeeCount": {
"fullTime": 7,
"partTime": 4
}
},
"sales": {
"salesByCategory": [
{
"categoryName": "Educational Toys",
"totalSales": 3299
}
],
"revenue": 3299
},
"promotionEvents": [
{
"eventName": "Massive Markdown Mania",
"promotionalDates": {
"startDate": {
"Year": 2024,
"Month": 9,
"Day": 21
},
"endDate": {
"Year": 2024,
"Month": 9,
"Day": 29
}
},
"discounts": [
{
"categoryName": "Remote Control Toys",
"discountPercentage": 6
},
{
"categoryName": "Building Sets",
"discountPercentage": 21
}
]
}
],
"company": "Relecloud",
"city": "North Jaylan",
"lastUpdated": {
"$timestamp": {
"t": 1733313006,
"i": 1
}
},
"storeOpeningDate": "2024-09-05T11:50:06.549Z"
}
示例 1:构造开始日期
聚合查询使用 $dateFromParts
从嵌套字段构造精确的 startDate 和 endDate 值,然后计算事件持续时间(以天为单位)。 它有助于标准化和分析以碎片日期格式存储的事件时间线。
db.stores.aggregate([
{
$match: { _id: "e6410bb3-843d-4fa6-8c70-7472925f6d0a" }
},
{
$unwind: "$promotionEvents"
},
{
$project: {
_id: 1,
startDate: {
$dateFromParts: {
year: "$promotionEvents.promotionalDates.startDate.Year",
month: "$promotionEvents.promotionalDates.startDate.Month",
day: "$promotionEvents.promotionalDates.startDate.Day"
}
}
}
}
])
该查询通过从嵌套升级数据中提取和组装日期部件来返回 _id
计算的 startDate。
{
"_id": "e6410bb3-843d-4fa6-8c70-7472925f6d0a",
"startDate": "2024-09-21T00:00:00.000Z"
}
相关内容
- 查看有关 从 MongoDB 迁移到适用于 MongoDB 的 Azure Cosmos DB (vCore) 的选项。
- 详细了解 与 MongoDB 的功能兼容性。