$dateToString

$dateToString運算子是用來將日期物件轉換成指定格式的字串。 它通常用於匯總管線,以格式化日期欄位來報告、查詢或顯示用途。 此運算元非常多用途,可讓您定義自定義日期格式。

語法

{
  $dateToString: {
    format: "<format_string>",
    date: <date_expression>,
    timezone: "<timezone>",
    onNull: "<replacement_value>"
  }
}

參數

參數 Description
format 指定輸出日期格式的字串。
date 要格式化的日期表達式。
timezone (選擇性)指定時區的字串。 如果未提供,則預設為UTC。
onNull (選擇性)如果欄位為date或遺漏,null則傳回的值。

格式規範

Symbol 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 值

此查詢會使用 lastUpdated_new將不存在的欄位YYYY-MM-DD時間戳記格式化為字串。$dateToString 考慮到日期遺失或 Null,它會透過 onNull 選項取代後援字串 “No date available”。

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"
  }
]