Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How do mongoengine filter field not null?

I want to filter data with category value, but I don't know how to do this in mongoengine.

I try:

data = Data.objects.exclude(category="").order_by('-datetime')[:500]  

But got error:

exclude() got an unexpected keyword argument 'category'

I didn't find the method in document, how do you do this?

like image 957
user2492364 Avatar asked Oct 19 '22 21:10

user2492364


2 Answers

I have the feeling you're mixing up two concepts : filtering documents, and returning document subsets.

Returning a document subset 

exclude tells mongo to return selected documents without the category field. It won't filter the documents, just return the same documents, but without the category field: document subsets. Stripping out what you don't need improves performance. exclude and only achieve the same goal, except exclude blacklists fields, while only whitelists fields.

Filtering documents

What you want is to filter documents using a Queryset:

data = Data.objects({'category':{'$ne':''}}).order_by('-datetime')[:500]

or using the double underscore syntax:

data = Data.objects(category__ne='').order_by('-datetime')[:500]

See the tutorial.

like image 150
Jérôme Avatar answered Oct 23 '22 10:10

Jérôme


The .exclude() method takes only positional arguments; fields name. That being you need to use a query operator to filter out document where category is empty string using category__ne=''

data = Data.objects(category__ne='').order_by('-datetime')[:500] 
like image 30
styvane Avatar answered Oct 23 '22 11:10

styvane