Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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

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

Thanks!

like image 618
Ron Avatar asked Aug 08 '12 15:08

Ron


People also ask

How do you query in MongoEngine?

The connect() function returns a MongoClient object. Using list_database_names() method available to this object, we can retrieve number of databases on the server. It is also possible to obtain list of collections in a database, using list_collection_names() method.

Which is better PyMongo or MongoEngine?

Both PyMongo and MongoEngine can be used to access data from a MongoDB database. However, they work in very different ways and offer different features. PyMongo is the MongoDB recommended library. It makes it easy to use MongoDB documents and maps directly to the familiar MongoDB Query Language.

How do I delete MongoEngine?

Deleting documents. To delete a document, call the delete() method. Note that this will only work if the document exists in the database and has a valid id .


1 Answers

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())
like image 102
Ross Avatar answered Oct 26 '22 22:10

Ross