문제

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?

도움이 되었습니까?

해결책

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.

라이센스 : CC-BY-SA ~와 함께 속성
제휴하지 않습니다 StackOverflow
scroll top