運算符會將 $currentDate 欄位的值設定為目前的日期,可以是 Date 或時間戳。 此運算子適用於追蹤上次修改文件的時間,或設定建立時間戳的時間。
語法
{
$currentDate: {
<field1>: <typeSpecification1>,
<field2>: <typeSpecification2>,
...
}
}
參數
| 參數 | Description |
|---|---|
field |
要設定為目前日期的功能變數名稱。 |
typeSpecification |
選擇性。 指定日期值的型別。 可以是 true [日期類型] 或 { $type: "timestamp" } 時間戳類型。 預設值為 true (Date)。 |
範例
請參考商店集合中的此範例檔。
{
"_id": "7954bd5c-9ac2-4c10-bb7a-2b79bd0963c5",
"name": "Lakeshore Retail | DJ Equipment Stop - Port Cecile",
"location": {
"lat": 60.1441,
"lon": -141.5012
},
"staff": {
"totalStaff": {
"fullTime": 2,
"partTime": 0
}
},
"sales": {
"salesByCategory": [
{
"categoryName": "DJ Headphones",
"totalSales": 35921
}
],
"fullSales": 3700
},
"promotionEvents": [
{
"eventName": "Bargain Blitz Days",
"promotionalDates": {
"startDate": {
"Year": 2024,
"Month": 3,
"Day": 11
},
"endDate": {
"Year": 2024,
"Month": 2,
"Day": 18
}
},
"discounts": [
{
"categoryName": "DJ Turntables",
"discountPercentage": 18
},
{
"categoryName": "DJ Mixers",
"discountPercentage": 15
}
]
}
],
"tag": [
"#ShopLocal",
"#SeasonalSale",
"#FreeShipping",
"#MembershipDeals"
],
"company": "Lakeshore Retail",
"city": "Port Cecile",
"lastUpdated": {
"$date": "2024-12-11T10:21:58.274Z"
}
}
範例 1:設定目前日期
若要將具有目前日期的欄位新增至 lastUpdated 商店文件,請使用$currentDate運算子建立具有目前日期的欄位作為日期物件。
db.stores.updateOne(
{ "_id": "2cf3f885-9962-4b67-a172-aa9039e9ae2f" },
{
$currentDate: {
"lastUpdated": true
}
}
)
此作業會傳回下列結果。
{
acknowledged: true,
insertedId: null,
matchedCount: 1,
modifiedCount: 1,
upsertedCount: 0
}
範例 2:設定目前的時間戳
若要同時新增日期欄位和時間戳記欄位來追蹤修改,請使用值為 true 且 typestamp 值的 $currentDate 運算子。
db.stores.updateOne(
{ "_id": "2cf3f885-9962-4b67-a172-aa9039e9ae2f" },
{
$currentDate: {
"lastModified": true,
"lastModifiedTimestamp": { $type: "timestamp" }
}
}
)
此作業會傳回下列結果
{
acknowledged: true,
insertedId: null,
matchedCount: Long("1"),
modifiedCount: Long("1"),
upsertedCount: 0
}
範例 3:更新巢狀字段
設定文件結構中巢狀欄位的目前日期。
db.stores.updateOne(
{ "_id": "2cf3f885-9962-4b67-a172-aa9039e9ae2f" },
{
$currentDate: {
"sales.lastSalesUpdate": true,
"staff.lastStaffUpdate": { $type: "timestamp" }
}
}
)
此作業會傳回下列結果。
[
{
"_id": "2cf3f885-9962-4b67-a172-aa9039e9ae2f",
"name": "First Up Consultants | Bed and Bath Center - South Amir",
"lastUpdated": ISODate("2025-02-12T10:30:45.123Z"),
"lastModified": ISODate("2025-02-12T10:30:45.123Z"),
"lastModifiedTimestamp": Timestamp(1739450445, 1),
"sales": {
"totalSales": 37701,
"lastSalesUpdate": ISODate("2025-02-12T10:30:45.123Z"),
"salesByCategory": [
{
"categoryName": "Mattress Toppers",
"totalSales": 37701
}
]
},
"staff": {
"totalStaff": {
"fullTime": 18,
"partTime": 17
},
"lastStaffUpdate": Timestamp(1739450445, 1)
}
}
]