MongoDB在mongoengine中使用OR子句 [英] MongoDB using an OR clause in mongoengine
问题描述
我正在使用python的mongoengine查询MongoDB,并且大部分时间都喜欢它,但是
I'm using python's mongoengine to query MongoDB, and have loved it for the most part, but I'm having an issue with an advanced query.
这是我的模特
class ContentItem(Document):
account = ReferenceField(Account)
creator = ReferenceField(User)
public = BooleanField(default=False)
last_used = DateTimeField(default=datetime.now)
我想查询一个特定帐户的所有ContentItem
,这些ContentItem
是由登录用户创建的还是公开的.这是我写的查询
I would like to make a query for all ContentItem
's that are of a particular account, and are either created by the logged in user or are public. Here's the query I wrote
query = ContentItem.objects.filter( (Q(account=account) & Q(public=True)) | (Q(account=account) & Q(creator=logged_in_user)) ).order_by('-last_used')
或:
query = ContentItem.objects.filter( Q(account=account) & ( Q(public=True) | Q(creator=logged_in_user) ) ).order_by('-last_used')
但是这些似乎是XOR,如果public
或creator
但不是两者都存在.这是预期的吗?
But these seem to be XOR where if either public
, or the creator
but not both. Is this expected?
我在俯视什么吗?我应该直接使用mongodb而不是mongoengine这样做吗?
Am I overlooking something? Should I do this directly with mongodb instead of mongoengine?
我当前的解决方法是进行两个不同的查询并合并结果,但是随着内容项"的数量变大,结果需要很长时间才能回来,因为我需要先获取所有项才能订购它们,从而失去了(django)分页结果的所有好处.
My current workaround is to make two different queries and combine the results, but as the # of Content Items gets larger the result is taking a long time to come back because I need to get all items before I can order them, thereby losing all the benefit of (django) paginated results.
推荐答案
在这种情况下,mongoengine文档显然不正确.而不是使用按位运算符&"和"|",则应使用标准运算符"and"和"or".
The mongoengine documentation is apparently incorrect in this case. Instead of using the bitwise operators "&" and "|", you should use the standard operators "and" and "or".
因此您的第一个查询变为:
So your first query becomes:
query = ContentItem.objects.filter( (Q(account=account) and Q(public=True)) or (Q(account=account) and Q(creator=logged_in_user)) ).order_by('-last_used')
这篇关于MongoDB在mongoengine中使用OR子句的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!