Pymongo:如何插入带有时间戳的文档

Pymongo : How to insert a document with a timestamp

我想在数据库中插入一个带有时间戳而不是日期的文档。 如果我插入以下文件:

data = {'dt': dt.datetime.today().timestamp()}

时间戳将作为双精度插入:

我想要的是这种类型的数据:

虽然 Mongo 确实有一个 timestamp 文档确实说明了以下内容:

The BSON timestamp type is for internal MongoDB use. For most cases, in application development, you will want to use the BSON date type. See Date for more information.

请注意,使用时间戳类型还可能存在不同驱动程序支持的问题以及有关操作员行为的问题。 pymongo 使用 datetime.datetime 对象来表示 MongoDB 文档中的日期和时间。由于您已经在使用 datetime,我建议将其保存为 Date 而不是时间戳。

如果出于某种原因您坚持使用 timestamp 类型,那么您需要使用 bson.timestamp 类型,如下所示:`

from bson.timestamp import Timestamp
import datetime as dt
timestamp = Timestamp(int(dt.datetime.today().timestamp()), 1)

只是为了添加一些额外的东西,自动创建的默认 _id 字段包含一个“时间戳”,您可以使用 ObjectId 的 generation_time 属性 检索它对象,而不必在例如中添加您自己的字段:

from pymongo import MongoClient

db = MongoClient()['mydatabase']

db.mycollection.insert_one({'a': 1})
record = db.mycollection.find_one({'a': 1})
print(record.get('_id').generation_time)

打印:

2021-03-14 17:08:51+00:00