연 $dateToParts 산자는 날짜 개체에서 개별 구성 요소(Year, Month, Day, Hour, Minute, Second, Millisecond 등)를 추출하는 데 사용됩니다. 연산자는 개별 날짜 구성 요소에 따라 데이터를 정렬, 필터링 또는 집계하는 등 특정 날짜 부분의 조작 또는 분석이 필요한 시나리오에 유용합니다.
문법
$dateToParts: {
date: <dateExpression>,
timezone: <string>, // optional
iso8601: <boolean> // optional
}
매개 변수
| 매개 변수 | Description |
|---|---|
date |
파트를 추출할 날짜 식입니다. |
timezone |
Optional. 날짜의 표준 시간대를 지정합니다. 제공되지 않으면 기본적으로 UTC로 설정됩니다. |
iso8601 |
Optional. true이면 연산자는 ISO 8601 주 날짜 달력 시스템을 사용합니다. 기본값은 false입니다. |
예시
스토어 컬렉션에서 이 샘플 문서를 고려합니다.
{
"_id": "0fcc0bf0-ed18-4ab8-b558-9848e18058f4",
"name": "First Up Consultants | Beverage Shop - Satterfieldmouth",
"location": {
"lat": -89.2384,
"lon": -46.4012
},
"staff": {
"totalStaff": {
"fullTime": 8,
"partTime": 20
}
},
"sales": {
"totalSales": 75670,
"salesByCategory": [
{
"categoryName": "Wine Accessories",
"totalSales": 34440
},
{
"categoryName": "Bitters",
"totalSales": 39496
},
{
"categoryName": "Rum",
"totalSales": 1734
}
]
},
"promotionEvents": [
{
"eventName": "Unbeatable Bargain Bash",
"promotionalDates": {
"startDate": {
"Year": 2024,
"Month": 6,
"Day": 23
},
"endDate": {
"Year": 2024,
"Month": 7,
"Day": 2
}
},
"discounts": [
{
"categoryName": "Whiskey",
"discountPercentage": 7
},
{
"categoryName": "Bitters",
"discountPercentage": 15
},
{
"categoryName": "Brandy",
"discountPercentage": 8
},
{
"categoryName": "Sports Drinks",
"discountPercentage": 22
},
{
"categoryName": "Vodka",
"discountPercentage": 19
}
]
},
{
"eventName": "Steal of a Deal Days",
"promotionalDates": {
"startDate": {
"Year": 2024,
"Month": 9,
"Day": 21
},
"endDate": {
"Year": 2024,
"Month": 9,
"Day": 29
}
},
"discounts": [
{
"categoryName": "Organic Wine",
"discountPercentage": 19
},
{
"categoryName": "White Wine",
"discountPercentage": 20
},
{
"categoryName": "Sparkling Wine",
"discountPercentage": 19
},
{
"categoryName": "Whiskey",
"discountPercentage": 17
},
{
"categoryName": "Vodka",
"discountPercentage": 23
}
]
}
]
}
예제 1: 필드에서 날짜 부분 추출
이 쿼리는 날짜를 연도, 월, 일 및 시간과 같은 구성 요소로 분할 $dateToParts 하는 데 사용합니다lastUpdated. 추가 처리를 위해 날짜의 개별 부분을 분석하거나 변환하는 데 도움이 됩니다.
db.stores.aggregate([
{
$match: { _id: "e6410bb3-843d-4fa6-8c70-7472925f6d0a" }
},
{
$project: {
_id: 0,
dateParts: {
$dateToParts: {
date: "$lastUpdated"
}
}
}
}
])
이 쿼리는 다음 결과를 반환합니다.
[
{
"dateParts": {
"year": 2024,
"month": 12,
"day": 4,
"hour": 11,
"minute": 50,
"second": 6,
"millisecond": 0
}
}
]
예제 2: 표준 시간대 사용
이 쿼리는 lastUpdated 특정 문서의 타임스탬프를 추출하고 $dateToParts 사용하여 연도, 월, 일 및 시간과 같은 날짜 부분으로 나눕니다. "미국/New_York" 표준 시간대를 포함하면 분석이 허용되며 UTC 대신 현지 시간을 반영합니다.
db.stores.aggregate([
{
$match: { _id: "e6410bb3-843d-4fa6-8c70-7472925f6d0a" }
},
{
$project: {
_id: 0,
datePartsWithTimezone: {
$dateToParts: {
date: "$lastUpdated",
timezone: "America/New_York"
}
}
}
}
])
이 쿼리는 다음 결과를 반환합니다.
[
{
"datePartsWithTimezone": {
"year": 2024,
"month": 12,
"day": 4,
"hour": 6,
"minute": 50,
"second": 6,
"millisecond": 0
}
}
]