Chris
Chris

Reputation: 119

How to query mongoengine by using contains in list?

If I have a collection with a list field similar to the below.

class Post(Document):
   tags = ListField(StringField())

Let's say I have a post with the tags: interesting, funny.

And if I want to search for posts with tags fulfill any of the search terms, how should I do?

Say if I put in the search terms "interesting" and "fantastic", the above post should be there in the result set.

I tried to read through documentation but seems like there is no such operator. "all" and "in" are similar but can't perform what I want.

Upvotes: 2

Views: 3411

Answers (1)

Ross
Ross

Reputation: 18111

This is actually just a simple query eg:

class Post(Document):
    tags = ListField(StringField())

>>> Post.drop_collection()
>>> Post(tags=["hello", "world"]).save()
>>> Post(tags=["cat", "dog"]).save()

>>> Post.objects(tags__in=['hello', 'cat']).count()
... 2

What this equates to is find any documents that have hello in tags. In would go a search where any of the items in the 'in' array match and all is where all items match - or in other words an exact match.

Upvotes: 7

Related Questions