MongoDB导入数据时timestamp不符合BSON UTC格式报错求助
问题:MongoDB导入/插入数据时timestamp字段报错的解决方法
问题描述
尝试用MongoDB Compass的「导入数据」功能导入如下JSON Lines格式的数据:
{"timestamp":"1728714859000","prio":"0"} {"timestamp":"1728714859000","prio":"0"}
导入时触发写入错误:
{"name":"WriteError","message":"'timestamp' must be present and contain a valid BSON UTC datetime value","index":1,"code":2,"op": {"timestamp":"1728714859000","prio":"0","_id":"67397afef3e6b1d4dc9c2f44"}}
后续尝试的操作及遇到的问题:
- 去掉
timestamp值的引号后,Compass提示「Parser cannot parse input: expected an object key」解析错误 - 手动添加
_id并将timestamp改为ISODate()格式后,仍触发「Parser cannot parse input: expected a value」错误 - 改用Python的pymongo插入
timestamp为毫秒级整数的记录,依然触发相同写入错误:
pymongo.errors.WriteError: 'timestamp' must be present and contain a valid BSON UTC datetime value, full error: {'index': 0, 'code': 2, 'errmsg': "'timestamp' must be present and contain a valid BSON UTC datetime value"}
问题根源
你的目标集合已经定义了针对timestamp字段的验证规则,要求该字段必须是有效的BSON UTC日期类型——而你尝试传入的字符串、普通整数,以及MongoDB Shell专属的ISODate()语法,都不符合这个验证规则的要求。
解决方法
1. Compass导入的正确数据格式
使用MongoDB支持的JSON扩展语法($date关键字)来表示日期,修改后的JSON Lines数据如下:
{"timestamp":{"$date":1728714859000},"prio":"0"} {"timestamp":{"$date":1728714859000},"prio":"0"}
导入时注意选择「JSON Lines」格式,不要选择普通JSON格式。
2. Pymongo插入的正确写法
在Python中需要将毫秒时间戳转换为UTC时区的datetime对象,再插入数据库:
from pymongo import MongoClient from datetime import datetime, timezone # 初始化连接 client = MongoClient("你的MongoDB连接字符串") db = client["目标数据库名"] collection = db["目标集合名"] # 将毫秒时间戳转为UTC datetime对象 timestamp_ms = 1728714859000 utc_datetime = datetime.fromtimestamp(timestamp_ms / 1000, timezone.utc) # 插入记录 collection.insert_one({"timestamp": utc_datetime, "prio": "0"})
3. 临时禁用验证规则(不推荐)
如果只是临时测试导入数据,可以暂时关闭集合的验证规则:
- 在MongoDB Compass中打开目标集合的「集合设置」
- 找到「验证规则」选项,暂时禁用或修改规则后再执行导入操作
内容的提问来源于stack exchange,提问作者Rowan Smith
相关产品推荐
相关产品推荐

