Neel
Neel

Reputation: 21243

MongoEngine python library filter query get native mongo syntax

There is different way to filter the mongo query provided by mongoengine python library to connect to MongoDB. We can use different Query operators.

But this is MongoEngine implementation, MongoDB can't understand that, mongoengine has to convert that to syntax understand by MongoDB native syntax.

For example:

model.objects(field__in=[1])

is actual query in MongoDB as

db.collection.find({field: {$in: [1]}})

or

models.objects(field__lt=5)

is actual query in MongoDB as

db.collection.find({field: {$lt: 5}})

I am looking for some method where I can pass field__in=[1] and it would return me {field: {$in: [1]}}.

I need this to generate aggregate $match. MongoEngine model.objects.aggregate will return pymongo.command_cursor.CommandCursor object and it not support filtering as supported by QuerySet means, I cant do like model.objects.aggregate(XXXX)(field__in=[1]).

I can do model.objects(field__in=[1]).aggregate(XXX) but this is wrong, we are doing filter before the aggregate, but I want to do filter on aggregate data.

Upvotes: 0

Views: 346

Answers (1)

Eric Lewis
Eric Lewis

Reputation: 36

There is a method in mongoengine that will provide this.

from mongoengine.queryset.transform import query

Without giving a source Document the results will be pretty generic.

>> query(title="hello")
{'title': 'hello'}

>> query(title__contains="hello")
{'title': 'hello'}

If you define a Document and provide it to the query, each field type will know to to processes the query correctly:

>> from mongoengine import Document, fields

>> class Test(Document):
>>    title = fields.StringField()

>> query(Test, title="hello")
{'title': 'hello'}

>> query(Test, title__contains="hello")
{'title': re.compile(r'hello', re.UNICODE)}

Upvotes: 2

Related Questions