

本文為英文版的機器翻譯版本，如內容有任何歧義或不一致之處，概以英文版為準。

# $dateToParts
<a name="dateToParts"></a>

5.0.1 和 8.0 版的新功能

Amazon DocumentDB `$dateToParts` 中的彙總運算子會傳回文件，其中包含日期和時間值的組成部分，例如年、月、日、小時、分鐘、秒和毫秒。

**參數**
+ `date`：要分段的日期和時間值。
+ `timezone`：（選用） 擷取日期部分時要使用的時區。如果未指定，則會以 UTC 傳回組件。
+ `iso8601`：（選用） 如果設定為 `true`，則傳回的文件會使用 ISO 8601 日期部分 (`isoWeekYear`、`isoWeek`、`isoDayOfWeek`)。預設值為 `false`。

## 範例 (MongoDB Shell)
<a name="dateToParts-examples"></a>

下列範例示範如何使用 `$dateToParts`運算子來傳回日期的個別部分。

**建立範例文件**

```
db.events.insertMany([
  { _id: 1, eventDate: ISODate("2023-04-01T10:30:15Z") },
  { _id: 2, eventDate: ISODate("2023-12-25T18:45:00Z") }
]);
```

**查詢範例**

```
db.events.aggregate([
  {
    $project: {
      _id: 1,
      parts: { $dateToParts: { date: "$eventDate" } }
    }
  }
])
```

**輸出**

```
[
  {
    "_id": 1,
    "parts": { "year": 2023, "month": 4, "day": 1, "hour": 10, "minute": 30, "second": 15, "millisecond": 0 }
  },
  {
    "_id": 2,
    "parts": { "year": 2023, "month": 12, "day": 25, "hour": 18, "minute": 45, "second": 0, "millisecond": 0 }
  }
]
```

## 程式碼範例
<a name="dateToParts-code"></a>

若要檢視使用 `$dateToParts`命令的程式碼範例，請選擇您要使用的語言標籤：

------
#### [ Node.js ]

```
const { MongoClient } = require('mongodb');

async function example() {
  const client = await MongoClient.connect('mongodb://<username>:<password>@<cluster-endpoint>:27017/?tls=true&tlsCAFile=global-bundle.pem&replicaSet=rs0&readPreference=secondaryPreferred&retryWrites=false');
  const db = client.db('test');
  const collection = db.collection('events');

  const result = await collection.aggregate([
    {
      $project: {
        _id: 1,
        parts: { $dateToParts: { date: "$eventDate" } }
      }
    }
  ]).toArray();

  console.log(result);

  await client.close();
}

example();
```

------
#### [ Python ]

```
from pymongo import MongoClient

def example():
    client = MongoClient('mongodb://<username>:<password>@<cluster-endpoint>:27017/?tls=true&tlsCAFile=global-bundle.pem&replicaSet=rs0&readPreference=secondaryPreferred&retryWrites=false')
    db = client['test']
    collection = db['events']

    result = list(collection.aggregate([
        {
            '$project': {
                '_id': 1,
                'parts': { '$dateToParts': { 'date': '$eventDate' } }
            }
        }
    ]))

    print(result)

    client.close()

example()
```

------