運算子 $toDate 會將指定的值轉換成日期類型。
語法
{
$toDate: <expression>
}
參數
| 參數 | Description |
|---|---|
expression |
可轉換成日期的運算式。 支援的格式包括:ISO 日期字串、自 Unix epoch 以來的毫秒數 (數字)、ObjectId 和 Timestamp。 如果運算式無法轉換成日期,作業就會傳回錯誤。 |
範例
請參考商店集合中的此範例檔。
{
"_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:將時間戳記轉換為日期
若要將 lastUpdated 欄位的值從 Unix 時間戳轉換成日期格式,請使用 $toDate 運算符執行查詢來進行轉換。
db.stores.aggregate([{
$match: {
_id: "905d1939-e03a-413e-a9c4-221f74055aac"
}
},
{
$project: {
name: 1,
lastUpdated: 1,
lastUpdatedAsDate: {
$toDate: "$lastUpdated"
}
}
}
])
此查詢會傳回下列結果:
[
{
"_id": "905d1939-e03a-413e-a9c4-221f74055aac",
"name": "Trey Research | Home Office Depot - Lake Freeda",
"lastUpdated": { "t": 1729983325, "i": 1 },
"lastUpdatedAsDate": ISODate("2024-10-26T22:55:25.000Z")
}
]