Mongodb 默认使用插入时的当前时间戳

Mongodb default with current timestamp on insert

是否可以将具有默认值的字段作为插入时的当前时间戳?可以通过更新来做到这一点:

self.db.history.insert(activity, { '$current_date': { 'timestamp': { '$type': 'timestamp' } } })

但是$current_date只适用于更新。

也许我应该在 Python 中创建一个时间戳,因为几毫秒或几秒不是问题。

如果要使用 pymongo 在 MongoDB 中插入包含当前日期的文档,请从标准库中导入 datetime.datetime

from datetime import datetime

collection.insert({ "created_date": datetime.now() }