$currentDate(当前时间)
最后更新:2026-10-09
$currentDate(当前时间)
$currentDate 将字段值设为当前时间,可存为日期(Date)或时间戳(Timestamp)。`{ $currentDate: { lastModified: true } }` 默认存 Date;`{ $currentDate: { lastModified: { $type: 'timestamp' } } }` 存 Timestamp。与客户端 new Date() 相比更精确,且避免服务器与客户端时差问题。
| 分类 | 更新字段 |
|---|---|
| MongoDB 版本 | 3.6+ |
| 示例语言 | mongosh (Shell) |
📝 语法
{ $currentDate: { <字段>: true | { $type: 'timestamp' | 'date' } } }
⚙️ 参数
| 字段 | 要设为当前时间的字段名。 |
|---|---|
| 类型 | true 存 Date;也可显式指定 'timestamp' 或 'date'。 |
返回值:更新结果文档
▶ 示例
请在本地安装的 mongosh 中执行以下命令(需已启动 mongod):
// $currentDate:记录修改时间
// true 默认存 Date 类型
db.articles.updateOne(
{ _id: 1 },
{ $currentDate: { lastModified: true } }
)
// 显式指定存 Timestamp
db.articles.updateOne(
{ _id: 1 },
{ $currentDate: { lastModified: { $type: 'timestamp' } } }
)
运行结果:
// 文档 lastModified 被设为服务器当前时间(Date 或 Timestamp)
📌 注意事项
- 字段不存在时自动创建
- Timestamp 用于需要排序或重复时间戳的场景
- 取的是服务器端时间,与客户端时区无关
🏷️ 相关标签
💡 相关案例
📚 相关教程
❓ 常见问题
Q$currentDate 和 $set: new Date() 有什么区别?
A$currentDate 在服务器端取值更精确统一;$set 用客户端时间,多客户端可能不一致。
Q能存 Timestamp 类型吗?
A能,{ $type: 'timestamp' } 显式指定。
Q$currentDate 会覆盖已有值吗?
A会,直接覆盖为当前时间。