

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

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

5.0.1 和 8.0 版的新功能

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

**參數**
+ `year`：日曆年。不使用 ISO 8601 組件時為必要。
+ `month`、`day`、`hour`、`minute`、`second`、`millisecond`： （選用） 剩餘的日期和時間元件。省略的元件預設為最低的有效值。
+ `isoWeekYear`、`isoWeek`、`isoDayOfWeek`：（選用） ISO 8601 日期元件。使用這些 而非 `year`、 `month`和 `day`來建構 ISO 8601 週日期的日期。
+ `timezone`：（選用） 建構日期時要使用的時區。如果未指定，則會使用 UTC。

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

下列範例示範如何使用 `$dateFromParts`運算子從個別元件建構日期。

**建立範例文件**

```
db.parts.insertMany([
  { _id: 1, y: 2023, m: 4, d: 1 },
  { _id: 2, y: 2023, m: 12, d: 25 }
]);
```

**查詢範例**

```
db.parts.aggregate([
  {
    $project: {
      _id: 1,
      constructedDate: {
        $dateFromParts: { year: "$y", month: "$m", day: "$d" }
      }
    }
  }
])
```

**輸出**

```
[
  { "_id": 1, "constructedDate": ISODate("2023-04-01T00:00:00Z") },
  { "_id": 2, "constructedDate": ISODate("2023-12-25T00:00:00Z") }
]
```

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

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

------
#### [ 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('parts');

  const result = await collection.aggregate([
    {
      $project: {
        _id: 1,
        constructedDate: {
          $dateFromParts: { year: "$y", month: "$m", day: "$d" }
        }
      }
    }
  ]).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['parts']

    result = list(collection.aggregate([
        {
            '$project': {
                '_id': 1,
                'constructedDate': {
                    '$dateFromParts': { 'year': '$y', 'month': '$m', 'day': '$d' }
                }
            }
        }
    ]))

    print(result)

    client.close()

example()
```

------