You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

PyMongo中Long类型字段执行$gt操作失败问题求助

解决MongoDB增量拉取时的bson编码错误

问题原因

错误bson.errors.InvalidDocument: cannot encode object: Decimal('1675286325369'), of type: <class 'decimal.Decimal'>的核心原因是:查询条件中$gt对应的max_created_date是Decimal类型,而MongoDB的BSON编码器无法直接将Decimal类型数值用于这类比较操作。全量拉取无需传入自定义查询条件,因此不会触发该编码问题。

解决方案

只需将Decimal类型的max_created_date转换为整数类型即可——因为MongoDB中存储的Epoch时间戳(毫秒/秒级)通常为整数格式,匹配整数类型的查询值才能正常执行$gt比较:

修改后的代码

# 将Decimal类型转换为整数
max_created_date_int = int(max_created_date)
query = {"createdTimeStamp": {"$gt": max_created_date_int}}
cursor = collection.find(query)

额外注意事项

  • 如果max_created_date是从其他数据库或数据源获取的,建议在获取阶段直接转换为整数,避免后续类型不匹配问题。
  • 确认MongoDB集合中createdTimeStamp字段的存储类型为整数(int64),若为Date类型,则需将查询值转换为datetime对象或MongoDB的ISODate格式,但根据描述,字段存储的是Epoch时间,因此整数转换是正确方向。

内容的提问来源于stack exchange,提问作者Anil Sarkar

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.08.02 11:40:12