$dayOfYear

运算符 $dayOfYear 从日期值中提取年份的日期,其中 1 表示 1 月 1 日。 它可用于根据一年中的日期对文档进行分组或筛选。

Syntax

{ $dayOfYear: <dateExpression> }

参数

参数 Description
<dateExpression> 要从中提取年份日期的日期表达式。

例子

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

{
  "_id": "e6410bb3-843d-4fa6-8c70-7472925f6d0a",
  "name": "Relecloud | Toy Collection - North Jaylan",
  "location": {
    "lat": 2.0797,
    "lon": -94.4134
  },
  "staff": {
    "employeeCount": {
      "fullTime": 7,
      "partTime": 4
    }
  },
  "sales": {
    "salesByCategory": [
      {
        "categoryName": "Educational Toys",
        "totalSales": 3299
      }
    ],
    "revenue": 3299
  },
  "promotionEvents": [
    {
      "eventName": "Massive Markdown Mania",
      "promotionalDates": {
        "startDate": {
          "Year": 2024,
          "Month": 9,
          "Day": 21
        },
        "endDate": {
          "Year": 2024,
          "Month": 9,
          "Day": 29
        }
      },
      "discounts": [
        {
          "categoryName": "Remote Control Toys",
          "discountPercentage": 6
        },
        {
          "categoryName": "Building Sets",
          "discountPercentage": 21
        }
      ]
    }
  ],
  "company": "Relecloud",
  "city": "North Jaylan",
  "lastUpdated": {
    "$timestamp": {
      "t": 1733313006,
      "i": 1
    }
  },
  "storeOpeningDate": "2024-09-05T11:50:06.549Z"
}

示例 1:提取年度日期

查询使用 $dayOfYear 运算符从 lastUpdated 时间戳中提取年份序号(1-366)。 它可用于按日历年度中的位置跟踪事件,例如季节性趋势或每周比较。

db.stores.aggregate([
  {
    $match: { _id: "e6410bb3-843d-4fa6-8c70-7472925f6d0a" }
  },
  {
    $project: {
      _id: 0,
      dayOfYear: { $dayOfYear: "$lastUpdated" }
    }
  }
])

结果显示发生的日历日编号 lastUpdated 。 在当前示例中,339 年 12 月 4 日为非年。