MongoEngine - Query - How to check if a ListField is empty or not set

11,547

Solution 1

Hi you can use $exists and $size:

import unittest
from mongoengine import *

class Test(unittest.TestCase):

    def setUp(self):
        conn = connect(db='mongoenginetest')

    def test_list_exists_or_has_size(self):

        class Post(Document):
            title = StringField(required=True)
            tags = ListField(StringField())

        Post.drop_collection()

        Post(title="Hello Stackoverflow").save()
        Post(title="Hello twitter", tags=[]).save()
        Post(title="Hello world", tags=['post', 'blog']).save()

        self.assertEqual(2, Post.objects(
                                Q(tags__exists=False) |
                                Q(tags__size=0)).count())

Solution 2

If you were looking for the reverse question (check if a list contains at least an element which implies that it also exists), here is how you can do it using a query dict for a change:

query = {}
query['tags__exists'] = True
query['tags__not__size'] = 0
for post in Post.objects(**query):
    print(post)

As per the MongoEngine documentation, the not operator can be used to negate a standard check as long as it precedes the query operator.

Share:
11,547

Related videos on Youtube

Ron
Author by

Ron

"Nothing is ever easy." — Zedd

Updated on June 04, 2022

Comments

  • Ron
    Ron almost 2 years

    how do I check if an ListField() attribute of a Mongo Class is not set or empty?

    Thanks!