python - bson.errors.InvalidDocument : key '$oid' must not start with '$' trying to insert document with pymongo

标签 python pymongo

我想从 json 文件中插入文档到集合中,它说 bson.errors.InvalidDocument: key '$oid' must not start with '$' 我该如何解决?

文档示例: [{"name": "Company", "_id": {"$oid": "1234as123541gsdg"}, "info": {"email": "test@gmail.com"}}]

最佳答案

bson.ObjectId 类在 Python 中表示 ObjectIds:

from bson import ObjectId

_id = ObjectId("5899e0aca600741755433908")

所以对于一个完整的例子:

from bson import ObjectId

collection.insert(
    {"name": "Company", "_id": ObjectId("5899e0aca600741755433908"),
     "info": {"email": "test@gmail.com"}})

为了加载 MongoDB 扩展 JSON 数据,使用 PyMongo 的 json_util.loads :

from bson.json_util import loads

json_str = '[{"name": "Company", "_id": {"$oid": "5899e0aca600741755433908"}, "info": {"email": "test@gmail.com"}}]'

data = loads(json_str)
print(data)

for doc in data:
    collection.insert(doc)

“loads()”将带有“$oid”的扩展 JSON 语法转换为实际的 ObjectId 实例。

关于python - bson.errors.InvalidDocument : key '$oid' must not start with '$' trying to insert document with pymongo,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/42089045/

相关文章:

python - 为什么Python需要更长的时间来对列表的副本进行排序?

python - 在 Windows 上部署 Python 程序并获取大型库依赖项

mongodb - pymongo/mongodb 高级查询

python - 如何按 1000 分块读取集合?

mongodb - pymongo MongoClient 连接到 ReplicaSet

python - mongo中查询某个时间范围内的数据

Python OOP : how to share a MongoDB connection with all classes

python - 多处理 Pool.map 函数问题

python - 在 plotly 中更改分组条形图的组内顺序

python - 无法调用“列表”对象来检查分数准确性?