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

$week(日期表达式)

适用对象: MongoDB vCore

运算符 $week 将日期的周数返回为介于 0 和 53 之间的值。 第 0 周从 1 月 1 日开始,后续几周从周日开始。 如果日期为 null 或缺失, $week 则返回 null。

语法

$week 运算符的语法如下:

{
  $week: <dateExpression>
}

或者,使用时区规范:

{
  $week: {
    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": ISODate("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,
      openingWeek: { $week: { $toDate: "$storeOpeningDate" } }
    }
  }
])

查询返回“storeOpeningDate”字段中相应日期值的周号。

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

示例 2:按开周对商店进行分组

本示例按打开的一周对存储进行分组进行分析。

db.stores.aggregate([
  {
    $project: {
      name: 1,
      openingWeek: { $week: { $toDate: "$storeOpeningDate" } },
      openingYear: { $year: { $toDate: "$storeOpeningDate" } }
    }
  },
  {
    $group: {
      _id: { week: "$openingWeek", year: "$openingYear" },
      storeCount: { $sum: 1 },
      stores: { $push: "$name" }
    }
  },
  { $sort: { "_id.year": 1, "_id.week": -1 } },
  { $limit : 3 } ])

查询组按其开幕周和年份存储。

  {
    "_id": { "week": 40, "year": 2021 },
    "storeCount": 1,
    "stores": [ "First Up Consultants | Bed and Bath Center - South Amir" ]
  },
  {
    "_id": { "week": 52, "year": 2024 },
    "storeCount": 1,
    "stores": [ "Trey Research | Home Office Depot - Lake Freeda" ]
  },
  {
    "_id": { "week": 50, "year": 2024 },
    "storeCount": 2,
    "stores": [
      "Fourth Coffee | Paper Product Bazaar - Jordanechester",
      "Adatum Corporation | Pet Supply Center - West Cassie"
    ]
  }