【发布时间】:2020-02-04 01:27:06
【问题描述】:
我正在尝试使用pymongo 将一些图像元数据存储到MongoDB。但是插入时出现错误。
#Data in Dictionary
gps = {'GPSInfo': {1: 'N', 2: ((38, 1), (54, 1), (3540, 100)), 3: 'E', 4: ((1, 1), (26, 1), (1920, 100)), 5: b'\x00', 6: (0, 1), 7: ((11, 1), (7, 1), (47, 1)), 16: 'T', 17: (5338, 65), 29: '2011:09:04'}}
import pymongo
mng_client = pymongo.MongoClient('localhost', 27017)
mng_db = mng_client['pic_db']
collection_name = 'pic_audit_log2'
db_cm = mng_db[collection_name]
# Insert data from a dictionary
db_cm.remove()
db_cm.insert(gps)
错误
InvalidDocument: documents must have only string keys, key was 1
我是否必须将所有数字字典键更改为字符串? 当我这样做时它会起作用。
d = {str(a):{str(c):d for c,d in b.items()} if isinstance(b,dict) else b for a,b in gps.items()}
# Insert data from dictionary
db_cm.remove()
db_cm.insert(d)
还有其他更好的选择吗?
【问题讨论】:
标签: python-3.x mongodb dictionary pymongo