適用於:
MongoDB 虛擬核心
運算符會將 $year
日期的年份傳回為四位數的數位(例如 2024 年)。 如果日期為 Null 或遺漏, $year
則傳回 null。
語法
$year
運算子的語法如下:
{
$year: <dateExpression>
}
或使用時區規格:
{
$year: {
date: <dateExpression>,
timezone: <timezoneExpression>
}
}
參數
說明 | |
---|---|
dateExpression |
解析為 Date、Timestamp 或 ObjectId 的任何運算式。 |
timezone |
選擇性。 要用於計算的時區。 可以是 Olson 時區標識碼(例如“America/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
}