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

4,162 views
Skip to first unread message

Kelum Perera

unread,
Oct 4, 2019, 8:08:43 AM10/4/19
to mongodb-user
Hi there,

I'm trying to load python dictionary into mongodb using pymongo library. 

I get the below error as there are numerical values in my dictionary keys.


# Code
import pymongo

mng_client = pymongo.MongoClient('localhost', 27017)
mng_db = mng_client['pic_db'] # Replace mongo db name
collection_name = 'pic_audit_log2' # Replace mongo db collection name
db = mng_db[collection_name]


testDictionery = {'EYData': [{1:100,'test1':'test'},{'test':100,'test1':'test'}]}

db.remove()
db.insert(testDictionery)

# Error i get
InvalidDocument: documents must have only string keys, key was 1

Appreciate it if someone can give a solution. 
I'm not sure how many keys in my real data. so I have to find a way to accommodate all keys in numeric type.  

Thanks,
Kelum Perera

Wan Bachtiar

unread,
Oct 14, 2019, 8:01:39 AM10/14/19
to mongodb-user

I get the below error as there are numerical values in my dictionary keys.

Hi Kelum,

You are receiving the error message because MongoDB field names should be in strings. Depending on your use case, you can just use string keys:

testDictionary = {'EYData': [{ "1": 100, "test1": "test"}, { "test":100, "test1": "test"}]}

If these keys are from a variable, then you can try to cast them using str(). i.e. str(variable).

Regards,
Wan.

Reply all
Reply to author
Forward
0 new messages