Mongoengine: Field name with leading underscore

Created on 15 Jan 2015  路  7Comments  路  Source: MongoEngine/mongoengine

I have a field in my schema called from_ and it seems like I can't query it using mongoengine.

E.g.:

Message.objects(from___ne="xxx")

I get an error like:

InvalidQueryError: Cannot resolve field "from"

Is there a work around for this?

Most helpful comment

For future reference for anyone else who runs into the issue, a work around is to use the mongodb_field parameter and use a "valid" field name, such as mongooseVersion:

class ExistingDocument(Document):
    mongooseVersion = IntField(mongodb_field="__v")

...

All 7 comments

Hi @rgrinberg,

Using the master branch (what is to become release 0.9) queries using fields with trailing underscores work just fine. If possible, I would suggest just upgrading your MongoEngine version to master.

However, since I know that's not always a possibility, you can achieve the same outcome with earlier versions by using a raw query:

Message.objects(__raw__={'from_': {'$ne': 'xxx'}})

Looks a bit ugly, but it works.

Thanks for the response. Would __raw_ work in conjunction with other query elements. E.g.

Message.objects(channel="xxx",__raw__={'from_': {'$ne': 'xxx'}})

Yes, at least in version 0.8. I haven't tested with any prior versions, but I would assume it to work the same.

Thank you very much. I'm using 0.8.x so it should work. Since this is closed in master I assume we can close this.

It doesn't seem like creating a Document that has field with a leading underscore is supported. In my case, I have an existing DB populated by Mongoose which adds a "__v" (that's two consecutive underscores) field for versioning. However, it is not able to be read into a MongoEngine document even when I declare:

class ExistingDocument(Document):
    __v = IntField()

current_docs = ExistingDocuments.objects

Throws "The field '__v' does not exist on the document 'ExistingDocument"

Is there an alternative way to declare properties with two leading underscores? It makes sense not to support it by default because of all the build-in functions, but interoperability with Mongoose (on the database-side) would be a nice feature.

For future reference for anyone else who runs into the issue, a work around is to use the mongodb_field parameter and use a "valid" field name, such as mongooseVersion:

class ExistingDocument(Document):
    mongooseVersion = IntField(mongodb_field="__v")

...

Thanks to @Matthalp; the correct syntax currently is:

class ExistingDocument(Document):
    mongooseVersion = IntField(db_field="__v")
Was this page helpful?
0 / 5 - 0 ratings