推荐答案
$currentDate 操作符用于将字段的值设置为当前日期或时间戳。它可以设置为 Date 类型或 Timestamp 类型,具体取决于指定的选项。
本题详细解读
1. 基本用法
$currentDate 操作符通常用于更新文档中的某个字段,将其值设置为当前日期或时间戳。它可以在 update 或 findAndModify 操作中使用。
2. 语法
{
$currentDate: {
<field1>: <typeSpecification>,
<field2>: <typeSpecification>,
...
}
}<field>:要更新的字段名。<typeSpecification>:可以是{ $type: "date" }或{ $type: "timestamp" },分别表示将字段设置为当前日期或时间戳。
3. 示例
假设有一个集合 users,其中包含以下文档:
{
"_id": 1,
"name": "Alice",
"lastLogin": null
}我们可以使用 $currentDate 操作符将 lastLogin 字段更新为当前日期:
db.users.update(
{ _id: 1 },
{ $currentDate: { lastLogin: { $type: "date" } } }
)更新后的文档将变为:
{
"_id": 1,
"name": "Alice",
"lastLogin": ISODate("2023-10-05T12:34:56.789Z")
}4. 使用时间戳
如果希望字段存储为时间戳而不是日期,可以使用 { $type: "timestamp" }:
db.users.update(
{ _id: 1 },
{ $currentDate: { lastLogin: { $type: "timestamp" } } }
)更新后的文档将变为:
{
"_id": 1,
"name": "Alice",
"lastLogin": Timestamp(1696516496, 1)
}5. 注意事项
$currentDate操作符只能用于更新操作,不能用于插入操作。- 如果字段不存在,
$currentDate会创建该字段并将其值设置为当前日期或时间戳。 $currentDate操作符是原子操作,确保在并发环境下也能正确更新字段值。