Unable to insert a dot '.' in a nested key via pymongo

hey all =]
I’m working with python and trying to insert a dict into one of my fields but I get an error message when trying to do so…
I was able to insert the same data via the mongo shell, so It’s probably not a server issue.

my python code looks like this:

    uri = f"mongodb+srv://{DB_USER}:{DB_PASSWORD}@{DB_URL}/{DB_NAME}"
    collection = pymongo.MongoClient(uri)[DB_NAME]['testcollection']
    my_dict_with_dots = {"my.key": "myValue"}
    collection.insert_one({"dict_with_dots": my_dict_with_dots})

The exception thrown is

key ‘my.key’ must not contain ‘.’

I also tried using bypass_document_validation but that didn’t produce any difference…

what am I missing?

server version - Atlas 4.4
pymongo version - 3.11.4

1 Like

Replace

my_dict_with_dots = {“my.key”: “myValue”}

with

my_dict_with_dots = { "my" : { "key" : "myValue" } }
1 Like

hey steevej, thanks for your answer, but this is not what I’m trying to achieve =[

1 Like

Please show the resulting document.

1 Like

there it is:
{ "_id" : ObjectId("60be0b745c6f5a0ce036387d"), "dict_with_dots" : { "my.key" : "myValue" } }

1 Like

In general, it is not recommended to use dot (.) within a field name for MongoDB document (see Dot Notation - Document Field Access). Though it is permissible in some cases (like in mongo shell), PyMongo is not allowing it (as per your own try and the resulting error). There is a related JIRA issue to learn something about it: PyMongo - dots allowed in field names when updating.

3 Likes

This is indeed the expected behaviour. Dots in field names is a bad practice and should be avoided.

Until support is added in the query language, the use of $ and . in field names is not recommended and is not supported by the official MongoDB drivers.

2 Likes