你当前正在访问 Microsoft Azure Global Edition 技术文档网站。 如果需要访问由世纪互联运营的 Microsoft Azure 中国技术文档网站,请访问 https://docs.azure.cn

$month (日期表达式)

适用对象: MongoDB vCore

运算符 $month 从日期值中提取月份部分,返回介于 1 和 12 之间的数字,其中 1 表示 1 月和 12 日表示 12 月。 此运算符对于季节性分析和每月报告至关重要。

语法

运算符的 $isArray 语法如下所示:

{
  $month: <dateExpression>
}

参数

DESCRIPTION
dateExpression 解析为 Date、Timestamp 或 ObjectId 的表达式。 如果表达式解析为 null 或缺失, $monthnull返回 。

示例:

让我们了解数据集中示例 JSON 的 stores 用法。

{
  "_id": "905d1939-e03a-413e-a9c4-221f74055aac",
  "name": "Trey Research | Home Office Depot - Lake Freeda",
  "location": { "lat": -48.9752, "lon": -141.6816 },
  "staff": { "employeeCount": { "fullTime": 12, "partTime": 19 } },
  "sales": {
    "salesByCategory": [ { "categoryName": "Desk Lamps", "totalSales": 37978 } ],
    "revenue": 37978
  },
  "promotionEvents": [
    {
      "eventName": "Crazy Deal Days",
      "promotionalDates": {
        "startDate": { "Year": 2023, "Month": 9, "Day": 27 },
        "endDate": { "Year": 2023, "Month": 10, "Day": 4 }
      }
    }
  ],
  "company": "Trey Research",
  "city": "Lake Freeda",
  "storeOpeningDate": ISODate("2024-09-26T22:55:25.779Z"),
  "lastUpdated": Timestamp({ "t": 1729983325, "i": 1 })
}

示例 1:从商店开张日期提取月份

此示例从商店开张日期中提取月份部分,以分析季节性开张模式。

db.stores.aggregate([
  { $match: {"_id": "905d1939-e03a-413e-a9c4-221f74055aac"} },
  {
    $project: {
      name: 1,
      storeOpeningDate: 1,
      openingMonth: {
        $month: "$storeOpeningDate"
      },
      openingMonthName: {
        $switch: {
          branches: [
            { case: { $eq: [{ $month: "$storeOpeningDate" }, 1] }, then: "January" },
            { case: { $eq: [{ $month: "$storeOpeningDate" }, 2] }, then: "February" },
            { case: { $eq: [{ $month: "$storeOpeningDate" }, 3] }, then: "March" },
            { case: { $eq: [{ $month: "$storeOpeningDate" }, 4] }, then: "April" },
            { case: { $eq: [{ $month: "$storeOpeningDate" }, 5] }, then: "May" },
            { case: { $eq: [{ $month: "$storeOpeningDate" }, 6] }, then: "June" },
            { case: { $eq: [{ $month: "$storeOpeningDate" }, 7] }, then: "July" },
            { case: { $eq: [{ $month: "$storeOpeningDate" }, 8] }, then: "August" },
            { case: { $eq: [{ $month: "$storeOpeningDate" }, 9] }, then: "September" },
            { case: { $eq: [{ $month: "$storeOpeningDate" }, 10] }, then: "October" },
            { case: { $eq: [{ $month: "$storeOpeningDate" }, 11] }, then: "November" },
            { case: { $eq: [{ $month: "$storeOpeningDate" }, 12] }, then: "December" }
          ]
        }
      }
    }
  }
])

查询从商店打开时间戳返回月份部分(9),表示 9 月。

{
  "_id": "905d1939-e03a-413e-a9c4-221f74055aac",
  "name": "Trey Research | Home Office Depot - Lake Freeda",
  "storeOpeningDate": ISODate("2024-09-26T22:55:25.779Z"),
  "openingMonth": 9,
  "openingMonthName": "September"
}