Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Why using integer as a key with pymongo doesn't work?

I've tried this with a larger data set in python and had issues, so i created a small test set, also in python with pymongo:

from pymongo import MongoClient
testColl = MongoClient().tDB.tColl
data = {'foo': 'bar', 'baz': {1: {'a': 'B'}}, '_id': 'AB123456789'}
testColl.insert(data)

This returns

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

replacing the 1 in the dictionary in baz with a 2 changes the error to key was 2 accordingly

Why is this? Am I missing something about ids in Mongo?

like image 203
John Avatar asked Feb 06 '14 01:02

John


1 Answers

I've submitted an edit to the title of your post considering it was somewhat misleading to the problem you are having. You were not trying to update an _id field as indicated but rather your Python Dictionary definition was incompatible with the BSON spec.

In this line:

data = {'foo': 'bar', 'baz': {1: {'a': 'B'}}, '_id': 'AB123456789'}

You have a numeric (integer) as the key value for, in Mongo terms, a document. Deriving from JSON, within the BSON spec this is not valid your keys must be Strings as required in the specification.

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

You need to keep all of your keys in your Python code as strings in order to be compliant.

data = {'foo': 'bar', 'baz': {'1': {'a': 'B'}}, '_id': 'AB123456789'}

Changing the representation of the key to a string fixes the problem.

As a note, consider your document structure as there are several disadvantages of using this type of notation (if you want to access a numerical index ) in a MongoDB documents collection over using an array.

like image 182
Neil Lunn Avatar answered Oct 28 '22 20:10

Neil Lunn