Skip to content Skip to sidebar Skip to footer

Mongodb Not Allowing Using '.' In Key

I'm trying to save a dictionary containing a special character '.' in key portion to the MongoDB. The error is presented below, which clearly states that the key must not contain a

Solution 1:

You can set check_keys to False according to the source:

 test.insert(d,check_keys=False)


 definsert(self, doc_or_docs, manipulate=True,
           safe=None, check_keys=True, continue_on_error=False, **kwargs):

It does indeed work:

In [28]: d = {'.aaa' : '.bbb'}

In [29]: test.insert(d,check_keys=False)
Out[29]: ObjectId('54ea604bf9664e211e8ed4e6')

The docstring states:

  • check_keys (optional): If True check if keys start with '$' or contain '.', raising :class:~pymongo.errors.InvalidName in either case.

You seem to be able to use any character apart from just the two $ or . so a leading underscore or any other character would be fine and probably a better option.

There is info in the faq about escaping :

In some cases, you may wish to build a BSON object with a user-provided key. In these situations, keys will need to substitute the reserved $ and . characters. Any character is sufficient, but consider using the Unicode full width equivalents: U+FF04 (i.e. “$”) and U+FF0E (i.e. “.”).

And the dot-notation faq explains why using . is not a good idea:

MongoDB uses the dot notation to access the elements of an array and to access the fields of an embedded document. To access an element of an array by the zero-based index position, concatenate the array name with the dot (.) and zero-based index position, and enclose in quotes:

Post a Comment for "Mongodb Not Allowing Using '.' In Key"