Mongoengine: Unable to insert dictionary having '.' in key names

Created on 13 Jul 2017  路  9Comments  路  Source: MongoEngine/mongoengine

class testcollection(Document):
    d1 = DictField() 
    bool_field = BooleanField(default=False)
    test_str = StringField(null=True)

Input operation:

testcollection(d1={'[email protected]':1})

Expected Result:
[Success in creation]

Actual Output/Error:
mongoengine.errors.ValidationError: ValidationError (testcollection:None) (Invalid dictionary key name - keys may not contain "." or "$" characters: ['d1'])

Most helpful comment

Since MongoDB 3.6, it looks like dots are valid within the field names.

https://docs.mongodb.com/manual/reference/limits/#Restrictions-on-Field-Names

Should I create a new issue to address this or can this be re-opened. I am willing to create a PR to address this once I know how you want to track this.

All 9 comments

That's a limitation of MongoDB itself, see https://docs.mongodb.com/manual/reference/limits/#Restrictions-on-Field-Names/

Is there not any alternative to overcome it?

Structure your data differently, e.g. use a list field of embedded docs, each with "email" and "number" fields (guessing the field names from your example). Structuring it this way also helps if you ever want to query for a particular email, since you can't really query on dict key names.

ok. thanks, got it!
Was expecting a hack for it!

Since MongoDB 3.6, it looks like dots are valid within the field names.

https://docs.mongodb.com/manual/reference/limits/#Restrictions-on-Field-Names

Should I create a new issue to address this or can this be re-opened. I am willing to create a PR to address this once I know how you want to track this.

This has to be part of mongoengine !

Is there any update on this .. still facing the issue.
It is now supported bu MongoDb.

Just wanted to bump this issue again. For those who need a workaround in the meantime and are using MongoDB > 3.6, I have found success by passing in the dictionary to the modify function. For example,

object.modify(set__some_dict={"foo.bar": "xyz"})

Of course, this isn't ideal, and code quality would be improved greatly if this issue gets resolved. The best scenario would be having the ability to do

object.some_dict = {"foo.bar": "xyz"}
...other things...
object.save()

Quick PR: #2193

Was this page helpful?
0 / 5 - 0 ratings