当你想读取数据时,是否可以在mongoengine中使用逻辑运算符

Is it possible to use logical operators in mongoengine when you want to read data

我用python mongoengine.

我想知道是否可以在对象中使用条件。

例如:

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

我知道我们可以使用 Q classRaw 在 json 模式下查询数据库,但我更喜欢 objects( A and B or C)

中的简单多重条件

通常很难肯定某些事情不能,但我认为这就是您问题的答案。如果您需要使用逻辑运算符,Q(或 raw)似乎是可行的方法。

进入更多细节,official documentation for Mongoengine 说:

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

暗示 Q 是在 MongoEngine 查询中使用逻辑运算符的方法。

稍后文档警告:

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).

最后,similar question was asked here in Whosebug and one of the comments 表示

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

简而言之,看来你不能覆盖orand运算符,Q是执行逻辑操作的推荐方式。

gmauch 是正确的,处理逻辑组合的最佳方法是 Q.

但是,对于您的特定示例,多个传递关键字参数的默认逻辑是 and

因此,

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

将仅 return Person 具有 "bob" 的 name 和 70 的 salary 的文档。它的功能等同于 (name=="bob") and (salary==70)

但是,对于除了非常简单的 and 条件序列之外的任何其他情况,请使用 Q.

而且,是的,文档没有提及隐式 and