Skip to content
Advertisement

Mongoengine: Querying using __not__contains but with lists instead of string

I have a list of topics that I want to filter out from ‘title’ field in News Database.

I want the solution to do the opposite of what __contains does, but contains works with string, and I want to give it a list in which it will filter out every news that will contain the words given in the list.

Example:

blacklist=["Facebook", "Apple"]

I want to use this list and filter out every news if its title contains words in blacklist.

Edit: I think I didn’t clarify my objective in above lines. Using blacklist declared above, in a list of news, exclude all news that ‘contains’ words in blacklist. (NOTE: I want to solve it using ‘list’ because this list i.e. blacklist might contain a lot of words.)

e.g. “Facebook is not privacy friendly” = excluded

“Apple may be privacy friendly” = excluded

“Bitcoin market crashed” = not excluded

Advertisement

Answer

You can combine multiple conditions with AND/OR through MongoEngine’s Q class

from mongoengine import connect, Document, StringField, Q

connect()

class TestDoc(Document):
    s = StringField()


TestDoc(s="Facebook is this").save()
TestDoc(s="and Twitter is that").save()
TestDoc(s="Something else").save()

query = Q(s__contains="Facebook") | Q(s__contains="Twitter")
TestDoc.objects(query)    # finds the 2 objects

# or dynamically from a list...
my_fancy_list = ['Facebook', 'Twitter']
dynamic_query = Q(s__contains=my_fancy_list.pop())
while my_fancy_list:
    dynamic_query |= Q(s__contains=my_fancy_list.pop())

TestDoc.objects(dynamic_query)    # finds the 2 objects
User contributions licensed under: CC BY-SA
9 People found this is helpful
Advertisement