简体   繁体   中英

Error when Inserting data with numerical keys into mongodb (GPS data in a python dictionary)

I'm trying to store some image metadata into MongoDB using pymongo . But I'm getting an error when inserting.

#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)

Error

InvalidDocument: documents must have only string keys, key was 1

Do I have to change all numerical dictionary keys into strings? It works when I do so.

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)

Is there any other better option?

The mongo shell will convert the integers into strings for you when inserting data, but pymongo won't. Your workaround is likely as good as any.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM