$currentDate (字段更新运算符)

适用对象: MongoDB vCore

运算符 $currentDate 将字段的值设置为当前日期,即日期或时间戳。 此运算符可用于跟踪上次修改文档的时间或设置创建时间戳的时间。

语法

$currentDate 运算符的语法如下:

{
  $currentDate: {
    <field1>: <typeSpecification1>,
    <field2>: <typeSpecification2>,
    ...
  }
}

参数

DESCRIPTION
field 要设置为当前日期的字段的名称。
typeSpecification 可选。 指定日期值的类型。 可以是 true (对于日期类型)或 { $type: "timestamp" } 时间戳类型。 默认值为 true (Date)。

示例:

让我们了解 stores 数据集中的示例 json 的用法。

{
  "_id": "2cf3f885-9962-4b67-a172-aa9039e9ae2f",
  "name": "First Up Consultants | Bed and Bath Center - South Amir",
  "location": {
    "lat": 60.7954,
    "lon": -142.0012
  },
  "staff": {
    "totalStaff": {
      "fullTime": 18,
      "partTime": 17
    }
  },
  "sales": {
    "totalSales": 37701,
    "salesByCategory": [
      {
        "categoryName": "Mattress Toppers",
        "totalSales": 37701
      }
    ]
  }
}

示例 1:设置当前日期

lastUpdated 具有当前日期的字段添加到存储文档。

db.stores.updateOne(
  { "_id": "2cf3f885-9962-4b67-a172-aa9039e9ae2f" },
  {
    $currentDate: {
      "lastUpdated": true
    }
  }
)

这将添加一个 lastUpdated 字段,将当前日期作为 Date 对象。

示例 2:设置当前时间戳

添加日期字段和时间戳字段以跟踪修改。

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)
  }
}