定义
$currentDateThe
$currentDateoperator sets the value of a field to the current date, either as a Date or a timestamp. The default type is Date.
兼容性
可以使用 $currentDate 查找托管在以下环境中的部署:
- MongoDB Atlas: The fully managed service for MongoDB deployments in the cloud
MongoDB Enterprise:基于订阅、自我管理的 MongoDB 版本
MongoDB Community:源代码可用、免费使用且可自行管理的 MongoDB 版本
语法
The $currentDate operator has the form:
{ $currentDate: { <field1>: <typeSpecification1>, ... } }
<typeSpecification> 可以为以下任一项:
布尔值为
true可将字段值设置为当前日期作为“日期”,或者显式指定类型的文档
{ $type: "timestamp" }或{ $type: "date" }。该操作符区分大小写,仅接受小写的"timestamp"或小写的"date"。
要在嵌入式文档或数组中指定 <field>,请使用点符号。
行为
从 MongoDB 5.0 开始,更新操作符按字典顺序处理具有基于字符串的名称的文档字段。具有数字名称的字段按数字顺序处理。详情请参阅更新操作符行为。
$currentDate sets the specified field to the date when $currentDate was run.
If the field does not exist, $currentDate adds the field to a document.
Starting in MongoDB 5.0, mongod no longer raises an error when you use an update operator like $currentDate with an empty operand expression ( { } ). An empty update results in no changes and no oplog entry is created (meaning that the operation is a no-op).
例子
创建一个包含以下文档的样本集合 customers:
db.customers.insertOne( { _id: 1, status: "a", lastModified: ISODate("2013-10-02T01:11:18.965Z") } )
以下操作将 lastModified 字段更新为当前日期,将 "cancellation.date" 字段更新为当前时间戳,并将 status 字段更新为 "D" 以及 "cancellation.reason" 至 "user request"。
db.customers.updateOne( { _id: 1 }, { $currentDate: { lastModified: true, "cancellation.date": { $type: "timestamp" } }, $set: { "cancellation.reason": "user request", status: "D" } } )
$currentDate sets the specified field to the date when $currentDate was run.
要验证更新:
db.customers.find()
更新后的文档类似于:
{ "_id" : 1, "status" : "D", "lastModified" : ISODate("2020-01-22T21:21:41.052Z"), "cancellation" : { "date" : Timestamp(1579728101, 1), "reason" : "user request" } }
The lastModified field is set to the date when $currentDate was run in the update example shown earlier.
以下项的聚合替代方案: $currentDate
更新方法可以接受聚合管道。具体来说,使用聚合阶段 $set 和聚合变量 NOW(表示当前日期时间)和 CLUSTER_TIME(表示当前时间戳),可以将前面的示例改写如下:
提示
要访问聚合变量,在变量前加上双美元符号
$$并用引号引起来。CLUSTER_TIME仅适用于副本集和分片集群。在整个管道中,
NOW和CLUSTER_TIME的值将保持不变。
db.customers.updateOne( { _id: 1 }, [ { $set: { lastModified: "$$NOW", cancellation: {date: "$$CLUSTER_TIME", reason: "user request"}, status: "D" } } ] )
操作完成后,可以查询集合以验证更新:
db.customers.find().pretty()
查询应返回以下文档:
{ "_id" : 1, "status" : "D", "lastModified" : ISODate("2020-01-22T21:02:18.994Z"), "cancellation" : { "date" : Timestamp(1579726934, 2), "reason" : "user request" } }