運算子 $dateFromParts 會從個別元件建構日期,例如年、月、日、小時、分鐘、秒和毫秒。 此運算子在處理個別儲存日期元件的數據時很有用。
語法
{
$dateFromParts: {
year: < year > ,
month: < month > ,
day: < day > ,
hour: < hour > ,
minute: < minute > ,
second: < second > ,
millisecond: < millisecond > ,
timezone: < timezone >
}
}
參數
| 參數 | Description |
|---|---|
year |
日期的年份元件。 |
month |
日期的月份元件。 |
day |
日期的日期元件。 |
hour |
日期的小時元件。 |
minute |
日期的分鐘元件。 |
second |
日期的第二個元件。 |
millisecond |
日期的毫秒元件。 |
timezone |
選擇性。 時區規格。 |
範例
請參考商店集合中的此範例檔。
{
"_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:建構開始日期
此查詢會使用 $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": "e6410bb3-843d-4fa6-8c70-7472925f6d0a",
"startDate": "2024-09-21T00:00:00.000Z"
}
]
相關內容
- 檢視從 MongoDB 遷移到 Azure DocumentDB 的選項。
- 閱讀有關 與 MongoDB 的功能相容性的更多資訊。