

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

# \$1currentDate
<a name="currentDate"></a>

`$currentDate` 運算子用於將欄位的值設定為目前的日期和時間。插入或更新文件時，此運算子對於自動更新具有目前時間戳記的欄位非常有用。

**參數**
+ `field`：要更新為目前日期和時間的欄位。
+ `type`：（選用） 指定要用於目前日期的 BSON 類型。可以是 `date` 或 `timestamp`。

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

下列範例示範如何在插入新文件時，使用 `$currentDate` 運算子將 `lastModified` 欄位設定為目前的日期和時間。

**建立範例文件**

```
db.users.insert({
  name: "John Doe",
  email: "john.doe@example.com"
})
```

**查詢範例**

```
db.users.updateOne(
  { name: "John Doe" },
  { $currentDate: { lastModified: true } }
)
```

**檢視更新的文件**

```
db.users.findOne({ name: "John Doe" })
```

**輸出**

```
{
  _id: ObjectId('...'),
  name: 'John Doe',
  email: 'john.doe@example.com',
  lastModified: ISODate('2025-10-25T22:50:29.963Z')
}
```

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

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

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

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

async function updateUserWithCurrentDate() {
  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 users = db.collection('users');

  await users.updateOne(
    { name: 'John Doe' },
    { $currentDate: { lastModified: true } }
  );

  console.log('User updated with current date');
  client.close();
}

updateUserWithCurrentDate();
```

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

```
from pymongo import MongoClient

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

    result = users.update_one(
        {'name': 'John Doe'},
        {'$currentDate': {'lastModified': True}}
    )

    print('User updated with current date')
    client.close()

update_user_with_current_date()
```

------