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

$year (日期表达式)

适用对象: MongoDB vCore

运算符 $year 将日期的年份作为四位数(例如 2024 年)返回。 如果日期为 null 或缺失, $year 则返回 null。

语法

$year 运算符的语法如下:

{
  $year: <dateExpression>
}

或者,使用时区规范:

{
  $year: {
    date: <dateExpression>,
    timezone: <timezoneExpression>
  }
}

参数

DESCRIPTION
dateExpression 解析为 Date、Timestamp 或 ObjectId 的任何表达式。
timezone 可选。 用于计算的时区。 可以是 Olson 时区标识符(例如“美国/New_York”)或 UTC 偏移量(例如“+0530”)。

示例:

让我们了解数据集中示例 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 }
      },
      "discounts": [
        { "categoryName": "Desks", "discountPercentage": 22 },
        { "categoryName": "Filing Cabinets", "discountPercentage": 23 }
      ]
    }
  ],
  "company": "Trey Research",
  "city": "Lake Freeda",
  "storeOpeningDate": "2024-12-30T22:55:25.779Z",
  "lastUpdated": { "t": 1729983325, "i": 1 }
}

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

该示例提取打开商店时的年份。

db.stores.aggregate([
  { $match: { "_id": "905d1939-e03a-413e-a9c4-221f74055aac" } },
  {
    $project: {
      name: 1,
      storeOpeningDate: 1,
      openingYear: { $year: { $toDate: "$storeOpeningDate" } }
    }
  }
])

查询返回打开存储的年份。

{
  "_id": "905d1939-e03a-413e-a9c4-221f74055aac",
  "name": "Trey Research | Home Office Depot - Lake Freeda",
  "storeOpeningDate": "2024-12-30T22:55:25.779Z",
  "openingYear": 2024
}

示例 2:查找在特定年份打开的商店

此示例查找在特定年份中打开的所有商店。

db.stores.aggregate([
  {
    $match: {
      $expr: {
        $eq: [{ $year: { $toDate: "$storeOpeningDate" } }, 2021]
      }
    }
  },
  {
    $project: {
      name: 1,
      city: 1,
      openingYear: { $year: { $toDate: "$storeOpeningDate" } },
      storeOpeningDate: 1
    }
  }
])

该查询返回在 2021 年打开的存储。

{
  "_id": "2cf3f885-9962-4b67-a172-aa9039e9ae2f",
  "city": "South Amir",
  "storeOpeningDate": "2021-10-03T00:00:00.000Z",
  "name": "First Up Consultants | Bed and Bath Center - South Amir",
  "openingYear": 2021
}