我想从 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/