作者:mobiledu2502881513 | 来源:互联网 | 2023-02-12 17:28
我想从json文件中将文档插入到集合中,它说bson.errors.InvalidDocument: key '$oid' must not start with '$'
如何解决它?
文件的例子:
[{"name": "Company", "_id": {"$oid": "1234as123541gsdg"}, "info": {"email": "test@gmail.com"}}]
1> A. Jesse Jir..:
使用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"的Extended JSON语法转换为实际的ObjectId实例.