翻訳は機械翻訳により提供されています。提供された翻訳内容と英語版の間で齟齬、不一致または矛盾がある場合、英語版が優先します。
$currentDate
$currentDate 演算子は、フィールドの値を現在の日付と時刻に設定するために使用されます。この演算子は、ドキュメントが挿入または更新されたときに、現在のタイムスタンプでフィールドを自動的に更新するのに役立ちます。
パラメータ
例 (MongoDB シェル)
次の例は、 $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')
}
コードの例
$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()