mongoengine - query how to filter by ListField size

mongodb, mongodb-query, mongoengine, python

Solution

Far from being the perfect solution, but you can do with a raw mongo query and the $where operator, for example:

posts = Post.objects.filter(__raw__={'$where': 'this.likes.length > 20'})

Another option, which should work faster, but is less clear in my opinion, is to check whether the 21th element exists:

posts = Post.objects.filter(likes__21__exists=True)

The second option only works if you're using MongoDB 2.2+

Source: Taken from these answers and applied to MongoEngine.

Problem

I have the following model: ``` class Like(EmbeddedDocument): user = ReferenceField(User,dbref=False) date = DateTimeField(default=datetime.utcnow,required=True) meta = {'allow_inheritance': False} class Post(Document): name = StringField(max_length=120, required=True) likes = ListField(EmbeddedDocumentField(Like)) ``` I would like to filter only Posts with more than 20 likes (ListField size greater than 20). I've tried to query using: ``` posts = Post.objects.filter(likes__size_gte=20) posts = Post.objects.filter(likes_gte=20) posts = Post.objects.filter(likes__gte=20) posts = Post.objects.filter(likes__size_gte=20) ``` None of them work. But if I use the exact match (ListField size exactly 20 likes) it works: ``` posts = Post.objects.filter(likes__size=20) ``` Comments?

Original source

Related problems