1

I use python mongoengine.

I would like to know if it is possible to use conditions in objects.

ex:

personnes =  Person.objects(name="bob" & salary=70)

I know we can use Q class to make that or Raw in json mode to query database but I prefer simple multiple condition in objects( A and B or C)

gmauch
  • 1,316
  • 4
  • 25
  • 39
Roots
  • 63
  • 6

2 Answers2

1

gmauch is correct, the best way to handle logical combinations is with Q.

However, for your specific example, the default logic for multiple passed keyword parameters is and.

Therefore,

personnes =  Person.objects(name="bob", salary=70)

will only return Person documents that have both a name of "bob" and a salary of 70. It's the functional equivalent of (name=="bob") and (salary==70)

But, for anything other than a very simple sequence of and'd conditions, use Q.

And, yes, the documentation is silent about the implicit and.

JohnAD
  • 879
  • 6
  • 6
  • Also, a heads up if you are using Django. Both Django and MongoEngine have a `Q`. Make sure you are using the right one. :) – JohnAD Oct 11 '18 at 01:57
0

It's usually hard to affirm that something can not be done, but I think that this is the answer for your question. Q (or raw) seems to be the way to go if you need to use logical operators.

Getting into more details, the official documentation for Mongoengine says:

if you need to combine a number of constraints using and and or this is made possible in MongoEngine through the Q class.

Implying that Q is the way to go to use logical operators in MongoEngine queries.

Later the docs warn:

You have to use bitwise operators. You cannot use or, and to combine queries as Q(a=a) or Q(b=b) is not the same as Q(a=a) | Q(b=b). As Q(a=a) equates to true Q(a=a) or Q(b=b) is the same as Q(a=a).

Finally, a similar question was asked here in StackOverflow and one of the comments states that

It's impossible to override the and/or in Python, instead you can override |/&. The source code of Q (mongoengine/queryset/visitor.py) and its history confirms that

In short, it seems you cannot override or and and operators and Q is the recommended way to perform logical operations.

gmauch
  • 1,316
  • 4
  • 25
  • 39