$currentDate (現在日時)
最終更新:2026-10-09
$currentDate (現在日時)
$currentDate は、フィールドに現在時刻を Date または Timestamp として設定します。`{ $currentDate: { lastModified: true } }` はデフォルトで Date を保存し、`{ $currentDate: { lastModified: { $type: 'timestamp' } } }` は Timestamp を保存します。クライアント側の new Date() より正確で、サーバーとクライアントの時計のずれを避けられます。
| カテゴリ | フィールド更新 |
|---|---|
| MongoDB バージョン | 3.6+ |
| 例の言語 | mongosh(シェル) |
📝 構文
{ $currentDate: { <field>: true | { $type: 'timestamp' | 'date' } } }
⚙️ パラメータ
| フィールド | 現在時刻を設定するフィールド。 |
|---|---|
| 型 | true は Date を格納します。'timestamp' または 'date' を明示的に指定できます。 |
戻り値:更新結果
▶ 例
以下のコマンドをローカルの mongosh で実行してください(mongod が起動済みである必要があります):
// $currentDate: 更新時刻を記録する
// true はデフォルトで Date を保存
db.articles.updateOne(
{ _id: 1 },
{ $currentDate: { lastModified: true } }
)
// Timestamp を明示指定
db.articles.updateOne(
{ _id: 1 },
{ $currentDate: { lastModified: { $type: 'timestamp' } } }
)
出力:
// lastModified にサーバー時刻が Date または Timestamp として設定される
📌 注意事項
- フィールドがなければ作成される
- Timestamp はソートや同刻の重複判定に適する
- クライアントのタイムゾーンに依存せずサーバー時刻を使う
🏷️ 関連タグ
💡 関連ケース
📚 関連チュートリアル
❓ よくある質問
Q$currentDate と $set で new Date() を使う違いは?
A$currentDate はサーバーの時計を一貫して参照します。$set はクライアント時刻を使うため、クライアントごとにずれる可能性があります。
QTimestamp を保存できますか?
Aはい。{ $type: 'timestamp' } を指定します。
Q$currentDate は既存の値を上書きしますか?
Aはい。現在時刻で上書きします。