在 MongoDB 中,可以使用 $currentDate
操作符來更新當(dāng)前時(shí)間。$currentDate
可以用于更新一個(gè)字段為當(dāng)前日期或當(dāng)前時(shí)間戳。
以下是使用 $currentDate
更新當(dāng)前時(shí)間的方法:
$currentDate
操作符和 { $type: "date" }
過濾器來更新字段為當(dāng)前日期。db.collection.updateOne(
{ _id: ObjectId("document_id") },
{ $currentDate: { field_name: { $type: "date" } } }
)
其中,collection
是集合的名稱,document_id
是要更新的文檔的 _id
,field_name
是要更新的字段的名稱。
$currentDate
操作符和 { $type: "timestamp" }
過濾器來更新字段為當(dāng)前時(shí)間戳。db.collection.updateOne(
{ _id: ObjectId("document_id") },
{ $currentDate: { field_name: { $type: "timestamp" } } }
)
同樣,collection
是集合的名稱,document_id
是要更新的文檔的 _id
,field_name
是要更新的字段的名稱。
注意:使用 $currentDate
更新字段時(shí),MongoDB 會(huì)將字段的類型轉(zhuǎn)換為日期或時(shí)間戳,如果字段原本不是日期或時(shí)間戳類型,會(huì)被更新為對(duì)應(yīng)的類型。