On this page
$currentDate
在本页面
Definition
$currentDate
- $currentDate运算符将字段的值设置为当前日期,即Date或timestamp。默认类型为Date。
在版本 3.0 中进行了更改:出于比较/排序的目的,MongoDB 不再将timestamp和Date数据类型视为等效。有关详细信息,请参见日期和时间戳比较 Sequences。
$currentDate运算符的格式为:
{ $currentDate: { <field1>: <typeSpecification1>, ... } }
<typeSpecification>
可以是:
布尔值
true
,用于将字段值设置为当前日期作为 Date,或者明确指定类型的文档
{ $type: "timestamp" }
或{ $type: "date" }
。运算符区分大小写,并且仅接受小写"timestamp"
或小写"date"
。
要在嵌入式文档或数组中指定<field>
,请使用dot notation。
Behavior
如果该字段不存在,则$currentDate将该字段添加到文档中。
Example
考虑users
集合中的以下文档:
{ _id: 1, status: "a", lastModified: ISODate("2013-10-02T01:11:18.965Z") }
以下操作将lastModified
字段更新为当前日期,将"cancellation.date"
字段更新为当前时间戳,并将status
字段更新为"D"
并将"cancellation.reason"
更新为"user request"
。
db.users.update(
{ _id: 1 },
{
$currentDate: {
lastModified: true,
"cancellation.date": { $type: "timestamp" }
},
$set: {
status: "D",
"cancellation.reason": "user request"
}
}
)
更新后的文档类似于:
{
"_id" : 1,
"status" : "D",
"lastModified" : ISODate("2014-09-17T23:25:56.314Z"),
"cancellation" : {
"date" : Timestamp(1410996356, 1),
"reason" : "user request"
}
}