运算符 $currentDate
将字段的值设置为当前日期,即日期或时间戳。 此运算符可用于跟踪上次修改文档的时间或设置创建时间戳的时间。
语法
$currentDate
运算符的语法如下:
{
$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
具有当前日期的字段添加到存储文档。
db.stores.updateOne(
{ "_id": "2cf3f885-9962-4b67-a172-aa9039e9ae2f" },
{
$currentDate: {
"lastUpdated": true
}
}
)
这将添加一个 lastUpdated
字段,将当前日期作为 Date 对象并生成以下结果:
{
acknowledged: true,
insertedId: null,
matchedCount: 1,
modifiedCount: 1,
upsertedCount: 0
}
示例 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)
}
}
相关内容
- 查看有关 从 MongoDB 迁移到适用于 MongoDB 的 Azure Cosmos DB (vCore) 的选项。
- 详细了解 与 MongoDB 的功能兼容性。